Node.js post method is failing with 500 error - node.js

I am new to node.js. I am developing node js application using VS 2015. Below is my server code (app.js)
In one of routes (trains.js) I defined a simple post method like below. Thing is it is working fine from localhost. But once I deploy to azure websites, POST method is throwing Internal server error.
Can some one help me with this? Please let me know if you need any further details.
//Here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var socketio = require('socket.io');
var global = require('./routes/globals.js');
GLOBAL._ = require('lodash');
GLOBAL.KEY = 'xxxxxxxxxxxxxxxxxxxxxx';
var availability = require('./routes/availability');
var fare = require('./routes/fare');
var stations = require('./routes/stations');
var pnr = require('./routes/pnr');
var route = require('./routes/route');
var trains = require('./routes/trains');
var app = express();
app.socket = socketio();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.set('port', process.env.PORT || 3000);
app.use('/availability', availability);
app.use('/fare', fare);
app.use('/stations', stations);
app.use('/pnr', pnr);
app.use('/route', route);
app.use('/trains', trains);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.socket.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
global.io = app.socket;
module.exports = app;
//Here is my train.js
var express = require('express');
var http = require('http');
var router = express.Router();
var utils = require("./utils.js");
var global = require('./globals.js');
router.get('/', function (req, res) {
var options = {
host: 'www.xxxxxxx.com',
path: '/test/xxxxxx/'
};
var parameters = {
fscode : 'xxxx',
tscode: 'xxxx',
//date: '',
//'class': '',
//orderby: '',
format: 'json',
pbapikey: '9xxxxxxxxa'
};
options.path += utils.getQueryString(parameters);
options.path += "pbapisign/" + utils.getHmacSHA1Signature(parameters);
callback = function (response) {
var data = "";
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
console.log(data);
res.send(data + "<h1>" + utils.hello() + "</h1>");
});
}
http.request(options, callback).on('error', function (error) {
console.log(error);
res.status(400).send(error.Message)
}).end();
});
router.post('/check', function (req, res) {
// console.log('Request -', req);
// console.log('Response -', res);
var data = {
request : "HELLO",
response: "VAMSI"
}
global.io.sockets.emit('NEW_CONTACT', data);
res.status(200).send('NEW DATA').end();
});
module.exports = router;

It seems that your code has not any obvious bug.
So if you can share some information for more detail, such as for error or deployment, I think it's helpful for investigating the issue.
Meanwhile, please try to install NTVS for your VS2015 and follow the wiki page Advanced Debugging - Remote Debugging on Windows Azure to debug your application.

Related

How can i get values of parameters using postman?

I am working on Node JS and PostgreSQL and I am creating REST web service using this. I have created a post method and calling web service through POSTMAN but unable to get parameter values in my function. Web service inserting null value in my PostgreSQL table. I am using Visual studio 2015 unable to debug code. How can I achieve this ?
queries.js
var promise = require('bluebird');
var options = {
// Initialization Options
promiseLib: promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://test:12345#localhost:8080/test';
var db = pgp(connectionString);
function getAllTask(req, res, next) {
debugger;
db.any('select * from tasklist')
.then(function (data) {
res.status(200)
.json({
status: 'success',
message: 'Retrieved ALL puppies',
data: data
});
})
.catch(function (err) {
return next(err);
});
}
function addTask(req, res, next) {
debugger;
//var task_name = req.param('task_name');
//var task_type = req.param('task_type');
var task_name = req.body.task_name;
var task_type = req.body.task_type;
console.log(req.body);
db.func('inserttask', [task_name, task_type])
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one task'
});
})
.catch(function (err) {
return next(err);
});
}
module.exports = {
getAllTask: getAllTask,
addTask: addTask
};
index.js
var express = require('express');
var router = express.Router();
var db = require('../queries');
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/api/tasklist', db.getAllTask);
router.post('/api/addtask', db.addTask);
module.exports = router;
server.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon iblic
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I am assuming that you are already using express js as framework for node js.
First of all you need to install body-parser module from npm:-
$ npm install body-parser --save
Once you have installed body-parser, add following code once after you have defined app variable:-
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // to support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // to support encoded bodies
Now you can access your post request body paramters as req.body.task_name and req.body.task_type
Hope it works and I am sorry if I have misunderstood your question.
You need to add Content-Type: application/json inside Headers when you send request through POSTMAN.

Error while running nodejs app on AWS Ubuntu using pm2

While starting nodejs with express application on AWS ubuntu using pm2, logs shows below error.
Below is my app.js file
// Packages
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//app.locals.basedir = path.join(__dirname, 'views');
global.__base = __dirname + '/';
var dbhelper = require('./routes/dbhelper.js');
var common = require('./routes/common.js');
var ErrorHandler = require('./routes/errorhandler.js');
var authenticationRepository = require(__base + 'repository/authentication.js');
// set up mustbe config
var mustBe = require("mustbe");
var mustBeConfig = require("./mustBeConfig");
mustBe.configure(mustBeConfig);
// Routes
var routes = require('./routes/index');
// Make database connection available to router
app.use(function (req, res, next) {
common.ActionOutput.Message = '';
common.ActionOutput.Results = [];
req.ActionOutput = common.ActionOutput;
req.ActionStatus = common.ActionStatus;
req.ApplicationCookies = common.ApplicationCookies;
req.Security = common.Security;
req.Constants = common.Constants;
console.log(req.url);
// Temp Keys
var key = common.Encrption('firstword|secondword');
var dkey = common.Decryption('3TYkoj9CgZZU+IdD+PAqC3U9xlyJuG40g2fXAJn3GB8=');
var key = req.get('Key');
var msg = null;
if (key == undefined || key == null || key == '')
msg = 'header key not found.';
else {
try {
var keys = common.Decryption(key).split('|');
if (keys.length < 2 || keys.length > 3)
msg = 'header key is incorrect.';
else
next();
} catch (err) {
msg = 'Unable to decrypt header value.';
}
}
if (msg != null) {
common.ActionOutput.Message = msg;
common.ActionOutput.Status = common.ActionStatus.Error;
return res.send(JSON.stringify(common.ActionOutput));
}
});
app.use('/', routes);
app.use(function (err, req, res, next) {
if (!err)
return next();
ErrorHandler.SaveErrorLog(req, res, null, err.message, err.stack, req.connection.remoteAddress, err.path);
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log('Exception: Not Found ' + req.url);
var APIKey = req.get('Key');
var UserKey = req.get('UserKey');
var DeviceToken = req.get('DeviceToken');
ErrorHandler.SaveErrorLog(req, res, UserKey, 'Resource not found!!!', '', req.connection.remoteAddress, req.url);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('shared/error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
var APIKey = req.get('Key');
var UserKey = req.get('UserKey');
var DeviceToken = req.get('DeviceToken');
ErrorHandler.SaveErrorLog(req, res, UserKey, 'Resource not found!!!', '', req.connection.remoteAddress, req.url);
});
process.on('uncaughtException', function (err, abc) {
console.log('uncaughtException: ' + err);
ErrorHandler.SaveErrorLog(null, null, null, 'UnCaught exception: ' + err.message, err.stack, 'IP', err.address);
});
module.exports = app;
app.listen(3000, function () {
console.log('Server starts on port: ' + 3000);
});
netstat says below which seems to be a problem to access it from outside. Application is running after changing port but not accessible.
Please suggest.

How do I use node on a live remote server (504 time out)

I am trying to deploy my node.js app to my web server. I have everything installed on the server side, and the app works locally. I just seem unable to connect when I try to upload it to the server. It tries to load and eventually gives me a 504 time out error.
Here's my code:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var multer = require('multer');
var app = express();
var fs = require('fs');
var mongoose = require('mongoose');
var unqID;
var http = require('http');
//http
http.createServer(function(req, res){
console.log('SmartMove Running');
mongoose.connect('mongodb://localhost/smartproperty');
var db = mongoose.connection;
var routes = require('./routes/index');
var articles = require('./routes/articles');
var categories = require('./routes/categories');
var manage = require('./routes/manage');
var manager = require('./routes/manager');
var adverts = require('./routes/adverts');
var upload = require('./routes/server');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/articles', articles);
app.use('/categories', categories);
app.use('/manage', manage);
app.use('/manager', manager);
app.use('/adverts', adverts);
//res.end('Done');
}).listen(8080, '127.0.0.1');
//end http
//upload
app.use(bodyParser.json());
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
//filename: function (req, file, callback) {
//callback(null, file.fieldname + '-' + Date.now());
//}
filename: function (req, file, callback) {
var advert = new Advert();
var qryId = advert._id;
callback(null, unqID + '-' + Date.now());
}
});
var upload = multer({ storage : storage }).array('userPhoto',2);
//app.get('/',function(req,res){
// res.sendFile(__dirname + "/index.html");
//});
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
console.log(req.body);
console.log(req.files);
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
//end upload
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
I have tried to see if it will load with just a res.end. This is successful, however, with that line removed nothing loads at all.
If anyone could help that would be great.
EDIT
Ok so i have managed to get it to depoy on my server but now this is presenting a different problem. all of the files have uploaded and i can see them, when the server is running though it fails to go to any routes, and it also seems like my CSS hasnt pulled through like in my development environment. Does anyone have any ideas why this may be, it still seems to be an issue on the server side which is why i edited, however if I am wrong to do this please let me know and i will create a new question.

Post function on NodeJs Deployed on aws returns Error:502

I am currently implementing a server that handles PayPal API calls from client and comunicates with PayPal's services in order to get token and create users in braintree.
The deployment went out well regarding elastic beanstalk. When i call the token method through the router i get the token and a success. The problem stands when i try to create a new braintree customer i get a cryptic 502 error. Any idea why? I am using the standard nginx setup from AIM listening on port 80. This is not a duplicate since the other similar questions did not resolved my issue.
Using nginx 1.8.0
index.js
var express = require('express');
var router = express.Router();
var http = require('http');
var braintree = require('braintree');
var gateway = braintree.connect({
environment: braintree.Environment.Sandbox,
merchantId: "xxxxxxxxxxxxxxx",
publicKey: "xxxxxxxxxxxxxxx",
privateKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
});
router.get('/', function(req,res) {
res.send('Iam a tree, a brain tree');
});
router.get('/token', function (req, res) {
gateway.clientToken.generate(null, function (error, response) {
res.json(response);
});
});
router.post('/createCustomer', function(req, res) {
var customer = req.body;
console.log(req.body);
gateway.customer.create({
firstName: customer.firstName,
lastName: customer.lastName,
company: customer.company,
email: customer.email,
phone: customer.phone,
fax: customer.fax,
website: customer.website
}, function (err, result) {
res.json(err,result);
});
});
module.exports = router;
main.js
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
And finally my www file
#!/usr/bin/env node
var debug = require('debug')('test');
var app = require('../main.js');
app.set('port', process.env.PORT || 8081);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Answering my question since i found the issue of the problem. The root of the problem was in the "/createCustomer", removing err from
res.json(err,result);
and changing it to
res.json(result);
Also i am not creating a customer with options(name, last name) just an empty one. To wrap it up the "/createCustomer" router function looks like this now.
/* Get Creates a new customer with the given params */
router.post('/createCustomer', function(req, res) {
var customer = req.body;
console.log(req.body);
gateway.customer.create({}, function(err, result) {
res.json(result);
});
});
This is a bit strange since the first version of the function was copied from the Braintree documentation about Node server setup. Anyway for the moment this workaround allows to create a customer link it with my current user on a custom Parse server and edit its properties later.

Socket.io not working with Express 4 without using diffrent port number

My application works when i specify a port number to socket.io that is diffrent from the server port number. The working code goes as follows:
This is my app.js file:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
var session = require('express-session');
var passport = require('passport');
var routes = require('./routes/index');
var auth = require('./routes/auth.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.set(process.env.PORT || 1337);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'mysessionsecret' }));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(configDB.url);
app.use('/', routes);
app.use('/auth', auth);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
var talk = require('./socket/talk.js')(app);
module.exports = app;
This is my talk.js file:
var init = function (app){
var server = require("http").createServer(app).listen(3000);
var io = require("socket.io").listen(server);
var socketioJwt = require("socketio-jwt");
var jwtSecret = require('../config/jwtSecret');
console.log("init");
io.set("authorization", socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));
io.sockets.on("connection", function (socket) {
console.log("connected");
socket.on("send", function (data) {
console.log(data);
var username = data.username;
var message = data.message;
var datetime = data.datetime;
socket.broadcast.emit("send", data);
});
socket.on("busy", function () {
socket.emit("busy");
socket.broadcast.emit("busy");
});
socket.on("free", function () {
socket.emit("free");
socket.broadcast.emit("free");
});
});
}
module.exports = init;
This is my script tag in index.ejs:
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
And finally this is my io connect from the client:
socket = io("http://localhost:3000/",{
query: 'token=' + tok
});
This works but the problem is that i want to publish my site to Azure but it is not possible to let a Azure website listen to diffrent ports. At least i think it is not possible.
One of the many things I tried is changing the talk.js file to this:
var init = function (app){
var server = require("http").createServer(app).listen(app.get('port'));
var io = require("socket.io").listen(server);
...
But i it doesn't work. I always get something along the lines of http://localhost/socket.io/socket.io.js not found
If i change the script tag in my index.ejs file to this
<script src="http://cdn.socket.io/socket.io-1.2.1.js"></script>
The socket.io.js file gets loaded but when i connect form te client side i get a continious 404 not found error.
I looked at a lot of solutions online but none of them work. I really don't know what i am doing wrong.
This error comes from the bin/www.js file being called before app.js when using npm start. A quick solution is to bypass www.js, which is only used to handle some common errors, as it is suggested in this answer.
This github repo is an implementation of this solution and can be used as a starting point for any Express.js + socket.io application.

Resources