app.use(bodyParser.json()); and bodyParser.urlencoded({ extended: true }) method unresolved - node.js

I am using webstorm and I have installed the body-parser module but bodyParser.json and bodyParser.urlencoded still gives a unresolved method error.
var express = require('express');
var connect = require('connect');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
port = process.env.PORT || 8080;
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
require('./routes.js')(app);
app.listen(port);
console.log('The App runs on port ' + port);
routes
var requests = require('config/requests');
var request = require('request');
module.exports = function(app) {
app.get('/', function(req, res) {
res.end("Node-Android-Chat-Project");
});
app.post('/login',function(req,res){
var name = req.body.name;
var mobno = req.body.mobno;
var reg_id = req.body.reg_id;
requests.login(name,mobno,reg_id,function (found) {
console.log(found);
res.json(found);
});
});
app.post('/send',function(req,res){
var fromu = req.body.from;
var fromn = req.body.fromn;
var to = req.body.to;
var msg = req.body.msg;
requests.send(fromn,fromu,to,msg,function (found) {
console.log(found);
res.json(found);
});
});
app.post('/getuser',function(req,res){
var mobno = req.body.mobno;
requests.getuser(mobno,function (found) {
console.log(found);
res.json(found);
});
});
app.post('/logout',function(req,res){
var mobno = req.body.mobno;
requests.removeuser(mobno,function (found) {
console.log(found);
res.json(found);
});
});
};

Trying installing the body-parser module again.
Use npm install body-parser --save

Related

Cannot get Express to find routes

I am working on making adjustments to teammates code and I haven't been able to understand how they have done their routing. I am attempting to have Express run a middleware script when an end-user goes to a new session of the web application.
I don't know what to test next to figure out how they have done their routing.
Main.js
// Dependencies
var http = require('http');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var busboy = require('connect-busboy');
var cors = require('cors');
var mongoose = require('mongoose');
// Configuration
var config = require('./config');
var twilio = require('twilio');
// Database
mongoose.connect(config.database);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
console.log('Connected to database');
});
var app = express();
app.set('port', process.env.PORT || 3000);
// Setup middleware
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.sessionSecret));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(busboy());
app.use(cors({
origin: true,
credentials: true
}));
app.all('/*',function(req,res){
twilio.notifyOnSession();
console.log('Message Sent');
})
var server = http.createServer(app);
var port = app.get('port');
server.listen(port);
console.log('Listening on port ' + port);
// Load server router
require('./router')(app);
/router/index.js
var path = require('path');
module.exports = function(app){
console.log('Initializing server routing');
require('./auth')(app);
require('./api')(app);
// Determine if incoming request is a static asset
var isStaticReq = function(req){
return ['/auth', '/api', '/js', '/css'].some(function(whitelist){
return req.url.substr(0, whitelist.length) === whitelist;
});
};
// Single page app routing
app.use(function(req, res, next){
if (isStaticReq(req)){
return next();
}
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
};
Your app.all('/*' is swallowing all requests before they can hit your router.
Don't do that.
I was able to resolve the issue by creating a new route with twilio.js and having the router look for the url twilio/new. Thanks all for the help.

How to capture response error/message in separate route?

I just want to capture the response error from a middleware function, it works if I write the code as follows:
var express = require('express');
var expressValidator = require('express-validator');
var app = express();
var bodyParser = require('body-parser');
var router = require('./routes');
//monk.mongoList();
app.use(bodyParser.urlencoded({extented:true}));
app.use(bodyParser.json());
app.use(expressValidator([]));
var port = process.env.PORT || 8978;
router.get('/',function(req,res,next) {
var error = Error('Article is not found');
next(error.message);
return res.send("Hello World!");
});
app.use(function(err,req,res,next) {
console.log(err + "TET");
})
app.listen(port);
but I want to separate the following code:
app.use(function(err,req,res,next) {
console.log(err + "TET");
})
and use it as follows:
app.js
var express = require('express');
var expressValidator = require('express-validator');
var app = express();
var bodyParser = require('body-parser');
var router = require('./routes');
//monk.mongoList();
app.use(bodyParser.urlencoded({extented:true}));
app.use(bodyParser.json());
app.use(expressValidator([]));
var port = process.env.PORT || 8978;
var test = require('./util/test')
app.use(test.logger);
app.use('/',router);
app.listen(port);
console.log('test node API ' + port );
util/test.js
module.exports.logger = function (err, req, res, next) {
console.log('LOGGED')
next()
}
/routes/index.js EDIT: I just edited the /routes/index.js file to make it more simple
var express = require('express');
var router = express.Router();
var url = require('url');
router.get('/api', function(req, res, next) {
var err = "this is error";
var error = Error (err)
var data = { data: "Succuss"}
if (err) {
next(error.message)
res.json({message:err})
}else {
res.json(data);
}
});
module.exports = router;
When add the above code, nothing appear in the console.

Unable to post on nodejs in heroku

I have a nodejs app running on Heroku. Here is the server.js file
var express = require('express')
, cors = require('cors')
, app = express();
var http = require('http').Server(app);
var io = require("socket.io").listen(http);
app.use(cors());
require('./modules/routes.js')(app,io);
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is my routes.js
"use strict";
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var time = require('express-timestamp');
var Promise = require('promise');
var momentjs = require('moment');
var _ = require('lodash');
var method = routes.prototype;
function routes(app, io) {
app.use(time.init);
app.use(cookieParser());
app.use(session({ secret: 'asdo8rter65edfgfd53wet34634632y4bluaq', resave: true, saveUninitialized: true }));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(bodyParser.json());
app.post('/testHeroku', function(req, res) {
console.log(req);
res.write(JSON.stringify({
process: "success"
}));
res.end();
});
}
method.getroutes = function() {
return this;
}
module.exports = routes;
I'm trying to access /testHeroku from an ionic app running in android emulator.
Ionic code:
vm.testHeroku = function(){
console.log('testing heroku');
var testdata = {
url: config.baseURL + 'testHeroku',
dataServer: {
serverTaskRequest: 'getUADSF'
}
}
runajax.runajax_function(testdata, function (testdataResponse) {
if (testdataResponse.process == 'success') {
alert(testdataResponse.process);
}
});
};
Here goes my config.baseURL = abcd-1234.herokuapp.com (This is example for the heroku app url)
I don't receive any return form the http call.
Code for run_ajax service
.service('runajax', ['$http', function ($http) {
this.runajax_function = function (request, callback) {
var url = request.url;
var dataServer = request.dataServer;
// console.log('runajax function called -> ' + url);
// console.log(dataServer);
$http.post(url, dataServer).success(function (data, status, headers, config) {
callback(data);
})
.error(function () {
callback(status);
});
}
}])
I got it working. There was an error with app.set('port', process.env.PORT || 5000); I changed it to var port = process.env.PORT || 8080;

Cannot GET/ Error In Node js With Heroku

I'm working on node js backend which receives user sms from android app using telerivet webhook API.everytime when i run the app atheroku it gives me cannot GET/ error ,my code for index.js is
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var WEBHOOK_SECRET = "62DZWMCCFFHTTQ44CG3WUQ94CTT7GAAN";
app.post('/telerivet/webhook',
bodyParser.urlencoded({ extended: true }),
function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message!,Our Backend Is Still in Alpha Stage,Hang Tight" }
]
});
}
res.status(200).end();
}
);
app.listen(process.env.PORT || 5000);
please help,where im i doing wrong
it gives me cannot GET/ error when i run the app on browser,and also doesnt reply for sms when testing with the app
I found the way out,this is my new code:
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello World!');
});
var bodyParser = require('body-parser');
var WEBHOOK_SECRET = "62DZWMCCFFHTTQ44CG3WUQ94CTT7GAAN";
app.post('/telerivet/webhook', bodyParser.urlencoded({ extended: true }),function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message!,Stay Tuned for Awesome " }
]
});
}
res.status(200).end();
}
);
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});

Nodejs Socket.io is not connecting

I'm connecting Socket in my App but the configuration is mismatched because of which socket is not connecting. What could be the problem? I'm referring to "Mastering Web Application Development with Express" for structuring
app.js
var express = require('express');
var app = express();
var morgan = require('morgan'); //HTTP request logger middleware for node.js
var flash = require('connect-flash');
var multiparty = require('connect-multiparty');
var cookieParser = require('cookie-parser');
var cookieSession = require('express-session');
var bodyParser = require('body-parser'); //Node.js body parsing middleware
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
var config = require('./config.js');
var passport = require('passport');
var fs = require('fs');
var sessionStore = new cookieSession.MemoryStore();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
morgan.token('id', function getId(req) {return req.id })
var accessLogStream = fs.createWriteStream(__dirname + '/log/systemAccessWithToken.log', {flags: 'a'})
app.use(assignId)
app.use(morgan(':id :method :url :response-time', {stream: accessLogStream}))
function assignId(req, res, next) {
next()
}
app.use(bodyParser.json()); //middleware that only parses json
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride(function(req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
var method = req.body._method;
delete req.body._method;
return method;
}
}));
app.use(cookieParser());
app.use(cookieSession({
store: sessionStore,
secret: config.sessionSecret,
cookie: {maxAge: config.sessionMaxAge}
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
if (app.get('env') === 'development') {
app.use(errorHandler());
}
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(express.static(__dirname + '/public'));
require('./app/passport')(passport); // pass passport for configuration
var socketcon = require('./app/mainSocket.js');
socketcon.socketconfig(app, io, sessionStore, cookieParser);
require('./routes/controller.js')(app, passport); // load our routes and pass
server.listen(config.port);
mainSocket.js
var modules = require('../externalModules.js');
var dbConnection = modules.dbConnection;
var cryptography = modules.cryptography;
var onlineUsers = {};
var onlineUsersSocketid = {};
exports.socketconfig = function(app, io, sessionStore, cookieParser) {
io.set('authorization', function(data, callback) {
if (!data.headers.cookie) {
return callback('No cookie transmitted.', false);
}
cookieParser(data, {}, function(parseErr) {
if (parseErr) {
return callback('Error parsing cookies.', false);
}
var sidCookie = (data.secureCookies && data.secureCookies['myuser.sid']) || (data.signedCookies && data.signedCookies['myuser.sid']) || (data.cookies && data.cookies['myuser.sid']);
sessionStore.load(sidCookie, function(err, session) {
if (err || !session || !session.passport.user) {
callback('socket Not logged in.', false);
} else {
data.session = session;
socketSession = session;
console.log("socketSession value " + JSON.stringify(socketSession));
callback(null, true);
}
});
});
});
io.sockets.on('connection', function(socket) {
console.log("socket connected");
console.log("socket.id " + socket.id);
socket.encryptedUserid = socketSession.passport.user.userId;
var devicetype = "web";
var secUserSalt = socketSession.passport.user.salt;
socket.userid = cryptography.crypto.fnDecryption(
socket.encryptedUserid, secUserSalt);
var isMobile = socketSession.passport.user.isMobile;
var devicetype = "web";
if (isMobile) {
devicetype = "mobile";
}
socket.on('user:join', function() {
//==============================develpoment(Aug21)====================
if (socket.userid in onlineUsersSocketid) {
onlineUsersSocketid[socket.userid].sockets_ids
.push(socket.id);
onlineUsersSocketid[socket.userid].devicetype
.push(devicetype);
} else {
onlineUsersSocketid[socket.userid] = {
"sockets_ids": [socket.id], // array for all sockets id of this user
"devicetype": [devicetype]
}
}
console.log("onlineUsersSocketid " + JSON.stringify(onlineUsersSocketid));
});
socket.on('disconnect', function() {
delete onlineUsersSocketid[socket.userid];
});
});
} // end of export module
What could be the issue?
Per the socket.io docs, these are two server-side initialization sequences that should work:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
or
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
You don't have either of these.

Resources