I've set up a simple node server and test program from the Node: up and running book. It seems to be working fine when I trace it through with debug but I'm curious why console.log doesn't output anything to the terminal.
Server, app.js
var express = require('express');
var http = require('http');
var app = express();
app.set('port', process.env.PORT || 8000)
app.use(express.urlencoded());
app.use(express.json());
app.use(express.logger('dev'));
var tweets = [];
app.get('/', function (req, res) {
res.send('Welcome to Node Twitter');
});
app.post('/send', function(req, res) {
if (req.body && req.body.tweet) {
tweets.push(req.body.tweet);
res.send({status:"ok", message:"Tweet received"});
} else {
// no tweet ?
res.send({status:"nok", message:"No tweet received"});
}
});
app.get('tweets', function (req, res) {
res.send(tweets);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Test script, test.js
var http = require('http');
assert = require('assert');
var opts = {
host: 'localhost',
port: 8000,
path: '/send',
method: 'POST',
headers: {'content-type':'application/x-www-form-urlencoded'}
}
var req = http.request(opts, function(res) {
res.setEncoding('utf8');
console.log("Sending test");
var data = "";
res.on('data', function(d) {
data += d;
})
res.on('end', function() {
assert.strictEqual(data, '{"status":"ok", "message":"Tweet received"}');
console.log("test");
})
})
req.write('tweet=test')
req.end
Would love some advice.
The event end never gets fired because you don't call the function req.end. You maintains the http request/connection open. You never finish it.
Try instead:
req.end();
Think about the difference between:
console.log('HI');
console.log;
Related
Was trying to connect to jaeger using HTTP request using nodejs but the spans are not reaching the jaeger endpoint. please help with this code snippet.,
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'servicename1',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
}
};
var options = {
tags: {
'servicename1': '1.0'
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);
Any help would be much appreciated!
Got it! We need to enable sampling strategy to reach the collector endpoint.
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'Jaeger_Service',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
},
'sampler': {
'type': 'const',
'param' : 0.1
}
};
var options = {
'logger': {
'info': function logInfo(msg) {
console.log('INFO ', msg)
},
'error': function logError(msg) {
console.log('ERROR', msg)
}
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
server.listen(8000);
console.log('Express server started on port %s', server.address().port);
I Have a Node app, I have three files and am trying to structure my node in a MVC pattern.
I want a way to put all my requires and variables in my server.js all the routes in my routes.js and my functions in my controller.js.
My router is fine and works.
How do I include the functions from controller in my server file
I have:
server.js
var configure = require('./router');
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
// get an instance of router
var router = express.Router();
configure(router);
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start
//
// // START THE SERVER
// // ==============================================
app.listen(port);
console.log('Server has started!! ' + port);
// apply the routes to our application
app.use('/', router);
router.js`
module.exports = function (router) {
// route middleware that will happen on every request
router.use(function (req, res, next) {
// log each request to the console
console.log(req.method, req.url);
// continue doing what we were doing and go to the route
next();
});
// home page route (http://localhost:8080)
router.get('/', function (req, res) {
res.send('im the home page!');
});
router.get('/login', function (req, res) {
res.send('this is the login form');
})
// process the form (POST http://localhost:8080/login)
.post('/login', function (req, res) {
console.log('processing'); // shows on console when post is made
res.send('processing the login form!'); // output on postman
});
};
controller.js
var password = 'gf.09';
var userkey = 'dfgg';
var emailAdmin = 'rt.r#rt.co.uk';
// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start
var firstFunction = function () {
return new Promise (function (resolve) {
setTimeout(function () {
app.post('/back-end/test', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
var secondFunction = function () {
return new Promise (function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
};
function thirdFunction(result) {
return new Promise (function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.error(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
// sequence of functions
Promise.all([firstFunction(), secondFunction()])
.then(thirdFunction);
What I have tried
var routers = require('./router');
var controller = require('./test');
// var controller = require('./test.js','./router' );
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
var app = express();
var port = process.env.PORT || 8080;
var router = express.Router();
routers(router);
controller(Promise);
and
module.exports = function (Promise) {
all functions
}
Problem is some of the variables are not available to controller.js so i get errors such as :
app.post('/back-end/controller', function (req, res) {
^
This is dead simple use same logic as you applied in your router.js.
Use something like below in controller.js:
exports.function_name = function(params, ...){
. . .
}
Then access these function by importing the controller.js
var controller = require('./controller.js');
controller.function_name(param..) # execute with required params and callback
If you want to return an object then you can do module.exports
module.exports = Promise.all([firstFunction(), secondFunction()]) .then(thirdFunction);
The controller object contain a promise now so
var controller = require('./controller.js');
controller object directly can be used as a promise no need to call a function now.
A better alternative is to export all the functions from controller.js and then in app.js you can use them with promise.
Promise.all([controller.firstFunction(), controller.secondFunction()]) .then(controller.thirdFunction);
I can't figure out how to write on a JSON file.
I'm working on a Single Application Page, using mostly AngularJS and Node.js
This is my code:
--index.html--
<script type="text/ng-template" id="pages/Animazione.html">
...
<td><input id="clickMe" type="button" value="clickme" ng-click="doPost()" /></td>
--app.js--
var App = angular.module('myMovie', ['ngRoute']);
...
.when('/Animazione', {
templateUrl : 'pages/Animazione.html',
controller : 'AnimazioneController'}
)
...
App.controller('AnimazioneController', ['$scope','$http', function($scope, $http) {
$http.get('Animazione.json').success(function(response)
{
$scope.myData=response;
})
.error(function()
{
alert("Si รจ verificato un errore!");
});
$scope.doPost = function()
{
writeOutputFile({test: 1});
};
}]);
--index.js-- (Server)
function writeOutputFile(data, success, fail) {
var fs = require('fs');
fs.writeFile('auth.json', JSON.stringify(data), function(error) {
if(error) {
console.log('[write output]: ' + err);
if (fail)
fail(error);
} else {
console.log('[write output]: success');
if (success)
success();
}
});
}
Is there any call or any function that I'm doing wrong?
As far as I know, you can't call a function directly which in the server via client.
To do this, define and end point in the server and from client make a call to that end point. Inside the handler for that end point in server call your function to write to file.
Eg: In server define /writefile endpoint like below (where express is used in server side) Add below contents to index.js
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');
var http = require('http');
var cors = require('cors');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors());
app.post('/writefile', function(req, res) {
var fileData = req.body.fileContent;
fs.writeFile('message.txt', fileData , function(err) {
if (err) {
res.status(500).jsonp({ error: 'Failed to write file' });
}
res.send("File write success");
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
Now your server is running in 3000 port.
In client:
$http({
method: 'POST',
url: 'http://localhost:3000/writefile', // Assuming your running your node server in local
data: { "fileContent": {"test": 1} } // Content which needs to be written to the file 'message.txt'
}).then(function(){
// Success
},
function(error) {
//error handler
console.error("Error occured::",error);
});
I'm trying to use nodejs as a layer between my public website and a server on the inside of our network.
I'm using express.js to create a simple REST api. The API endpoint should trigger a request call to a webservice, and return the result.
But the request call inside my .get() function doesn't do anything.
I want to return the result from the nested call to be returned.
Code:
// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
//Port
var port = process.env.PORT || 8080;
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.get('/invoice', function(req, res){
res.send('Express is workiung on IISNode')
});
app.get('/invoice/api/costumer=:customerId&invoice=:invoiceId', function(req, res){
res.send('Customer ID: ' + req.params.customerId + ' Invoice ID: '+ req.params.invoiceId)
var url = 'http://xxx/invapp/getinvoice?company='+req.params.customerId+'S&customerno=13968&invoiceno='+req.params.invoiceId+'';
request('http://www.google.com', function (error, response, body) {
res.send(body);
})
});
// Start server
app.listen(port);
console.log("API is running on port " + port);
Any suggestions?
You can write in this way
// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
//Port
var port = process.env.PORT || 8080;
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.get('/invoice', function(req, res){
res.send('Express is working')
});
app.get('/invoice/api/costumer=:customerId&invoice=:invoiceId', function(req, res){
var url = 'http://xxx/invapp/getinvoice?company='+req.params.customerId+'S&customerno=13968&invoiceno='+req.params.invoiceId+'';
request(url, function (error, response, body) {
var data={
body:body,
customerID:req.params.customerId,
invoiceID:req.params.invoiceId
};
res.send(data);
});
});
// Start server
app.listen(port);
console.log("API is running on port " + port);
Please find the snippet I am using. Hope this helps for you as well.
var body="";
function callyourservice(customerId,invoiceId,callback) {
var options = {
uri : url + 'costumer=:customerId&invoice=:invoiceId',
method : 'GET'
}
request(options, function (error, response, body) {
console.log(response);
if (!error && response.statusCode == 200) {
res = body;
}
else {
res = 'Not Found';
}
callback(res);
});
}
callyourservice("customerId value","invoiceId value", function(resp){
body=JSON.stringify(resp);;
});
You can write callyourservice inside a get method from client like
app.get('/'){
}
You can try doing it the node way using pipe
var http = require('http');
http.createServer(function(request, response) {
var proxy = http.createClient(9000, 'localhost')
var proxyRequest = proxy.request(request.method, request.url, request.headers);
proxyRequest.on('response', function (proxyResponse) {
proxyResponse.pipe(response);
});
request.pipe(proxyRequest);
}).listen(8080);
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to port 9000!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
You can find the reference here
I have a problem with my nodejs server. Here is my code
server.js
global.jQuery = global.$ = require('jquery');
var express = require('express'),
path = require('path'),
menu = require("./routes/menu");
var sql = require("mssql");
var http = require("http");
var io2 = require("io");
var app = express();
var serve = http.createServer(app);
var io = require('socket.io')(serve);
var recordset2;
var port = 8080;
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine','jade');
/* app.use(express.favicon());*/
app.use(app.router);
app.use(express.static(path.join(__dirname+'public')));
});
app.get('/:viewname', menu.viewname);
io.on('connection', function (socket) {
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('chat', function (msg) {
socket.broadcast.emit('chat', msg);
});
});
var dbConfig = {
server: "localhost",
database: "MyDatabase",
user: "sa",
password: "sa",
port: 1433
};
function getConnected() {
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM Countries").then(function (recordset) {
console.log("Recordset:", recordset);
conn.close();
}).catch(function (err) {
console.log("Error!!!!");
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log("Error!!!! ----");
console.log(err);
});
}
getConnected();
app.listen(port);
client's code
var socket = io();
$(function () {
$('#get-button').on('click', function () {
console.log("CLICK");
var msg = "HIIII";
socket.emit('chat', msg);
});
});
I'm trying to make a connection between server and client by socket, but it returns me the following error:
Error: Failed to lookup view 'socket.io' in views directory C:\Radio/views;
at Function.app.render (C:\Radio\node_modules\express\lib\application.js:493:17)
at ServerResponse.res.render (C:\Radio\node_modules\express\lib\response.js:798:7)
at exports.viewname (C:\Radio\routes\menu.js:2:9)
at callbacks (C:\Radio\node_modules\express\lib\router\index.js:164:37)
at param (C:\Radio\node_modules\express\lib\router\index.js:138:11)
at param (C:\Radio\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Radio\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (C:\Radio\node_modules\express\lib\router\index.js:173:5)
at Object.router (C:\Radio\node_modules\express\lib\router\index.js:33:10)
at next (C:\Radio\node_modules\express\node_modules\connect\lib\proto.js:193:15
Could you help me understand why? I saw there is another similar topics but none of the solutions there helped.
I found a solution two minutes after posting this topic.
global.jQuery = global.$ = require('jquery');
var express = require('express'),
path = require('path'),
menu = require("./routes/menu");
var sql = require("mssql");
var http = require("http");
var io2 = require("io");
var app = express();
var port = 8080;
var ser = app.listen(port); //<-----------This solved my problem.