Node JS req.body undefined - javascript

I've looked through quite a bit of other posts and I'm very lost with this.
I can run a console.log(req) and get the following output
ServerResponse {
...
req:
IncomingMessage {
...
url: '/my-endpoint',
method: 'POST',
statusCode: null,
statusMessage: null,
...
body: { foo: 'bar' },
_body: true,
...
route: Route { path: '/my-endpoint', stack: [Object], methods: [Object] } },
...
Looks solid, so I would expect to do console.log(req.body) and get { foo: 'bar' } back in the console...but nope, getting undefined
After research, I found that it may be something with my app.js file and specifically with a body-parser, however, I have all of that already
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 http = require('http');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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')));
//Home Page Rendering
var index = require('./routes/index');
app.use('/', index);
// All other routes are kept in the `routes` module
require('./routes')(app);
module.exports = app;
routes.js
module.exports = function routing(app) {
var apiClient = require('./services/apiClient');
app.post('/get-device-info', function(err, req, res){
console.log("/get-device-info routes");
apiClient(req, res);
});
};
apiClient.js
module.exports = function callApi(req, res){
console.log(req);
console.log(req.body)
};
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Here's what I've tried
app.use(express.bodyParser());
Ensuring that the incoming request is explicitly declaring application/json
Declaring body parser.json in other ways
Adding a config function

Your problem is that Express doesn't use error first callbacks for its route handlers. The below code won't work because the app.post handler doesn't have the signature (req, res) => {}. In the below code err is equal to req, req is equal to res, and res is equal to next.
// routes.js
module.exports = function routing(app) {
var apiClient = require('./services/apiClient');
app.post('/get-device-info', function(err, req, res){
console.log("/get-device-info routes");
// Assuming the request is correct
// the value of body will be the request body
console.log(res.body)
apiClient(req, res);
});
};`
There are 3 different route callback signatures you can use in Express
(req, res) => {} - This is the most basic and defines a route that just cares about the request and response
(req, res, next) => {} - This is middleware callback signature which looks like a basic route callback but, it also assigns the next object which tells Express to call the next matching route.
(err, req, res, next) => {} - This is the error handling route callback and you only need 1 per Express Router Middleware or Express App. It gets called if next(err) is called within a Route or Middleware. More specifically, if next() isn't called with a string or nothing it will skip all remaining Middleware and Routes and go straight to the error handler. You can read more about it in the Express Docs
You'll need to change the route definition to
app.post('/get-device-info', (req, res) => {
apiClient(req, res)
})
Or you could even do this
module.exports = app => {
let apiClient = require('./services/apiClient')
app.post('/get-device-info', apiClient)
}

Try this, since it worked for me.
First declare app and then the bodyParser, since bodyParser is used within app:
const app = express();
const bodyParser = require('body-parser');
Then have these lines below:
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

Related

All routes except the index route showing an Error 404 while developing on the Express Application Generator

I am building a day planner, and while I was setting the routes I noticed I am receiving a 404 for every routes other than the main Home page route ie, index or "/".
This is app.js file
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var calendarRouter = require('./routes/calendar');
var app = express();
//Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb+srv://<user-name>:<password>#cluster0.3xw67.gcp.mongodb.net/<db-name>?retryWrites=true&w=majority';
mongoose.connect(mongoDB, { useNewUrlParser: true , useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/calendar', calendarRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
This is the calendar.js route
var express = require('express');
var router = express.Router();
var schedule_controller = require('../controllers/scheduleController');
router.get('/', schedule_controller.index);
router.get('/calendar/create', schedule_controller.schedule_create_get);
router.post('/calendar/create', schedule_controller.schedule_create_post);
router.get('/calendar/:id/delete', schedule_controller.schedule_delete_get);
router.post('/calendar/:id/delete', schedule_controller.schedule_delete_post);
router.get('/calendar/:id/update', schedule_controller.schedule_update_get);
router.post('/calendar/:id/update', schedule_controller.schedule_update_post);
router.get('/calendar/event/:id', schedule_controller.schedule_details);
router.get('/events', schedule_controller.schedule_list);
module.exports = router;
This is the index.js route, I did a redirect here!
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.redirect('/calendar');
});
module.exports = router;
And here is the Controller for the calendar.js route.
var Schedule = require('../models/schedule');
exports.index = function(req, res) {
res.send('NOT IMPLEMENTED: Site Home Page');
};
exports.schedule_list = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule List');
};
exports.schedule_details = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule Detail: ' + req.params.id);
};
exports.schedule_create_get = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule create GET');
};
exports.schedule_create_post = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule create POST');
};
exports.schedule_delete_get = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule delete GET');
};
exports.schedule_delete_post = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule delete POST');
};
exports.schedule_update_get = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule update GET');
};
exports.schedule_update_post = function(req, res) {
res.send('NOT IMPLEMENTED: Schedule update POST');
};
Okay I found the bug it was me using index url that is / which I redirected to /calendar. And I have been using the rest of the url routes without calling the redirected one ie, /calendar.
I tried calling the routes with /calendar/calendar and it works!
I don't yet know clearly how to explain this. I hope fellow stackoverflow'ers could explain why this is happening.
Here's me trying a noob explanation!
Redirecting index route / to another url route, changes the main url route of the website(address). So all the sub routes which is everything other than the index route should explicitly call the redirected route (new address). Because every-time we call the old address the redirection changes it to the new one. Making the old address a dead one.
(Humour : I would like to point out an example considering numbers. It's like whole numbers and natural numbers. Redirection is when the whole number changes to natural number.)

node-postgres queries not returning anything in Express routes async routes

I'm trying to run a simple query from an express route:
var router = require('express-promise-router')()
const { Pool } = require('pg')
const pool = new Pool({
user: 'user',
password: 'password',
host: 'host',
port: 1234,
database: 'db'
})
router.get('/', async (req, res) => {
console.log('OK')
try {
const { rows } = await pool.query('Select VERSION()')
console.log(rows)
}
catch(e) {
console.log(e)
}
console.log('DONE')
})
module.exports = router
'OK' Prints after sending the request but rows, e, or 'DONE' never print. I'm following the async/await method directly from https://node-postgres.com/guides/async-express.
I've also came across a thread for koa-router where people were having issues with async await calls because of some middle-ware they added that wasn't synchronous
https://github.com/ZijianHe/koa-router/issues/358.
I'm not sure what middle-ware would cause this but here's my app.js that initializes all middle-ware:
var createError = require('http-errors');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require("cors");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var dataRouter = require("./routes/data");
var uploadRouter = require("./routes/upload")
var fundingRouter = require('./routes/chartData/fundingOverview')
var testRouter = require('./routes/test')
var authRouter = require('./routes/auth')
var session = require('express-session')
var MongoStore = require('connect-mongo')(session)
var passport = require('passport')
const config = require('config')
const mongo = config.get('mongo')
const mongoose = require('mongoose')
mongoose.connect(mongo, {
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
}).then(res => {
console.log('connected')
}).catch(err => {
console.log(err)
})
var express = require('express');
const mountRoutes = require('./routes')
var app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json())
mountRoutes(app)
app.use(cors())
var sessionMiddleWare = session({
secret: 'top session secret',
store: new MongoStore({ mongooseConnection: mongoose.connection }),
resave: true,
saveUninitialized: true,
unset: 'destroy',
cookie: {
httpOnly: false,
maxAge: 1000 * 3600 * 24,
secure: false, // this need to be false if https is not used. Otherwise, cookie will not be sent.
}
})
app.use(sessionMiddleWare)
// Run production React server on Node server
if(process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
// End Run production React Server on Node Server
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use('/upload', uploadRouter)
// app.use('/', indexRouter);
// app.use('/users', usersRouter);
// app.use('/data', dataRouter)
// app.use('/funding', fundingRouter)
// app.use('/login', usersRouter)
// app.use('/auth', authRouter)
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
// next(createError(404));
// });
// 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'm mounting the routes directly after body parser. That's the only middle-ware that's called before the routes and is required in order for me to get data into the back end.
I'm able to execute that simple query by putting it into a script file and running 'node test.js' (I.E without the router) and it works fine so I know it's not a problem with node-postgre.
I know this is a problem with the call stack not being totally synchronous but I'm confused as to what's not at this point. I even made the axios call on the front-end async/await with no luck (I don't think it was necessary though).
Any guidance would be help a lot.
EDIT:
I created a fresh express skeleton and hooked my front-end to make a call to a route on the new express server with the same code, it worked. It led me to discover the call wasn't being completed because I was running the server with Nodemon. When I start the server using 'yarn start' the async calls get processed correctly. The question now is what in nodemon makes async router calls not work?
You need to finish the request/response cycle in your middleware.
So in your code:
router.get('/', async (req, res) => {
console.log('OK')
try {
const { rows } = await pool.query('Select VERSION()')
console.log(rows)
res.status(200).json(rows)
}
catch(e) {
console.log(e)
res.status(500).json(e)
}
console.log('DONE')
})

Trying to send data from Reactjs Component to express app using axios

I'm working on a project that uses ReactJS typescript for the front-end, express for the back-end, and MongoDB for the database.
The main issue I am having is that I want to somehow send data from my React component to the express app so that it can query and add things to the database.
Currently, I have the express server running on http://localhost:9000, and the React app on http://localhost:3000, and I can connect them using routes.
My express app looks like the following:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require('./routes/testAPI');
var testAddUser = require('./routes/addUser');
const MongoClient = require('mongodb').MongoClient;
const mongoose = require('mongoose');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/testAPI", testAPIRouter);
app.use("/addUser", testAddUser);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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');
});
const dbRoute = 'mongodb+srv://Adminname:fjfeinjd#pawornaw-b4vzg.gcp.mongodb.net/test?retryWrites=true&w=majority';
mongoose.connect(dbRoute,
{useNewUrlParser: true})
.then(() => console.log("Connected to MongoDB"))
.catch(err => console.error("Could not connected to Mongo"));
module.exports = app;
and my React Component is this, minus import statements. The render function only contains a button that has an onlclick that executes doThing()
constructor(props: any) {
super(props);
this.state = {
showHomePage: true,
showAnimalUploadSearch: false,
showProfile: false,
showAnimal: true,
apiResponse: "",
fName: "bob"
};
this.changeView = this.changeView.bind(this);
// this.callAPI = this.callAPI.bind(this);
// this.componentWillMount = this.componentWillMount.bind(this);
this.doThing = this.doThing.bind(this);
}
callAPI() {
fetch("http://localhost:9000/testAPI")
.then(res => res.text())
.then(res => this.setState({apiResponse: res}))
.catch(err => err);
}
componentWillMount(): void {
this.callAPI();
}
changeView() {
this.setState({showHomePage: !this.state.showHomePage});
this.setState({showAnimalUploadSearch: !this.state.showAnimalUploadSearch});
this.setState({showAnimal: true});
this.setState({showProfile: false});
}
doThing() {
Axios.post('http://localhost:9000/testAPI', ({firstName: this.state.fName}))
.then(res => console.log(res));
}
and finally, testAPI.js looks like this
const router = express.Router();
const axios = require('axios');
router.get('/', function(req, res, next) {
//res.send('API is working properly');
axios.get('http://localhost:3000')
.then(res => console.log("got it"))
.catch(err => err);
});
module.exports = router;
I want to be able to access and use the data that is sent from my react component so that I can query my database with user input in the future. The API does connect with my React code, and when the testAPI function only contains these lines:
const router = express.Router();
const axios = require('axios');
router.get('/', function(req, res, next) {
res.send('API is working properly');
});
module.exports = router;
the message can be displayed on my react app in the browser via the state.
If anyone could help me see what I am doing wrong, or maybe give me a clue as to what other options I can try, please let me know.
Thank you.
When you send post request from client side, it will be in body property of req object
const router = express.Router();
// you shoud listen post request
router.post('/', function(req, res) {
const { body } = req;
// do somethin with data which you recieved in body, save to database for example
// and send response to the client
res.json({ message: 'your data was saved'});
});
module.exports = router;
to send data to client use:
router.get('/', function(req, res) {
res.json({ data: 'Some data'}); // or res.send('some text') to send plain text
});

Req.Body is returning "undefined" values

I have added body-parser to my application app.js file. I have a routes folder and a controllers folder which handles my request.
Initially, I did not have body-parser added to my application. When I added body-parser and console logged req.body I got an empty object. When I console logged req.body.email, req.body.password, and req.body.displayName values from postman were read as undefined.
app.js
let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
let bodyParser = require('body-parser');
let assert = require('assert');
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
let usersRouter = require('./routes/user');
let app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/user', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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');
});
// MongoDB Connection
const db = {};
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect(process.env.MONGODB_CONNECT_URL, (err, client) => {
// Connection works dont worry about it
});
module.exports = app;
routes/user.js
const express = require('express');
const router = express.Router();
const user = require('../controllers/user');
router.post('/', user.createUser);
router.delete('/:id', user.deleteUser);
router.get('/:id', user.loginUser);
module.exports = router;
controllers/user.js
const bcrypt = require('bcryptjs');
const Joi = require('joi');
const ObjectId = require('mongodb').ObjectID;
exports.createUser = async (req, res, next) => {
console.log('Request body: ', req.body);
const email = req.body.email;
const password = req.body.password;
const displayName = req.body.displayName;
console.log('Email: ', email);
console.log('Password: ', password);
console.log('Display name: ', displayName);
};
Please make sure that you are adding content-type header in postman content-type : application/json also in body tab select raw and beside raw select json from drop-down list.
Check this
https://i.stack.imgur.com/ZDhcl.png
You are probably trying to send form-data with Postman which sends a multipar body, body parser cannot handle multipart bodies. For handling multipart bodies you have to use a different module, I normally use multer.
With multer installed you just have to include it and it as middleware (under you body-parser for instance) using none() since in this case you want to handle text-only multipart body (More information about this in multer docs
let multer = require('multer');
app.use(multer().none());
Besides that I wanted to mention you are including two body parsers in your code, the express body parser
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
and an external body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Pick one, you don't need both, the best option for me would be to keep the one that comes with express, this way you don't have to install any more external packages.

'app.use() requires a middleware function' - Passport and Node Error

I'm trying to add local authentication to my node.js app. After following the tutorial on: https://scotch.io/tutorials/easy-node-authentication-setup-and-local I have run into error: "TypeError: app.use() requires a middleware function".
I think this is related to the app.use(indexRoutes) in my app.js file but I'm not sure how to fix this? Any help would be greatly appreciated.
Here is my code so far:
app.js:
var express = require('express'),
session = require("express-session"),
bodyParser = require('body-parser'),
app = express().use(bodyParser.json()), //creates express http server
passport = require('passport'),
sanitizer = require('express-sanitizer'),
mongoose = require("mongoose"),
cookieParser = require('cookieparser'),
dotnev = require('dotenv').config(),
https = require('https'),
flash = require('connect-flash'),
fs = require('fs'),
config = require('./config/config'),
_ = require("underscore");
require('./config/passport')(passport);
var indexRoutes = require("./routes/index")(app, passport);
app.use(bodyParser.urlencoded({extended: true}));
app.use(sanitizer());
app.use(express.static(__dirname + "/public")); //tells express to serve the contents of the public directory
app.use(cookieParser);
//no longer need to specify that the view files are .ejs
app.set("view engine", "ejs");
app.use(session({
secret: "akjjkjnisaiuu8998323jdkadsih892rhoisdfasl",
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 1200000
}
}));
app.use(passport.initialize);
app.use(passport.session());
app.use(flash());
app.use(indexRoutes);
mongoose.connect(process.env.MONGOLAB_URL, { useNewUrlParser: true });
index.js:
var express = require("express"),
router = express.Router(),
_ = require("underscore"),
User = require("../models/user"),
auth = require("../routes/auth"),
config = require('../config/config'),
freshbooks = require("../modules/freshbooks"),
quickbooks = require("../modules/quickbooks");
module.exports = function(router, passport){
//------------------------------------//
//***------------ROUTES------------***//
//------------------------------------//
router.get("/", function(req, res) {
res.render("landing");
});
router.get("/register", auth.optional, function(req, res) {
res.render("register");
});
router.get("/login", auth.optional, function(req, res) {
res.render("login");
});
router.get("/admin", isLoggedIn, function(req, res) {
res.render('admin', {
user : req.user // get the user out of session and pass to template
});
});
//------------------------------------//
//***-------------AUTH-------------***//
//------------------------------------//
router.post('/register', passport.authenticate('local-signup', {
successRedirect : '/admin', // redirect to the secure profile section
failureRedirect : '/register', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
router.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
}
Thanks in advance for any help!
In app.js
var { registerIndexRoutes } = require("./routes/index");
var indexRoutes = registerIndexRoutes(router, passport);
app.use(indexRoutes);
and index.js
const registerIndexRoutes = function(router, passport){
//------------------------------------//
//***------------ROUTES------------***//
//------------------------------------//
router.get("/", function(req, res) {
res.render("landing");
});
return router;//important;
}
module.exports = { registerIndexRoutes };
It will help you.
You're getting that error because, this function, module.exports = function(router, passport){, is not a valid middleware.
From express docs: Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle.
The syntax goes:
function(req, res, next) {
// Implement the middleware function based on the options object
next()
}
req: HTTP response argument to the middleware function, called "res" by convention.
res: HTTP request argument to the middleware function, called "req" by convention.
next: Callback argument to the middleware function, called "next" by convention.
When you invoked this function, function(router, passport){:
var indexRoutes = require("./routes/index")(app, passport);
indexRoutes, contains the return value of function(router, passport) which does not return a middleware function (It returns undefined).
Two ways you can solve the issue:
Change your import:
// remove this line and put the below instead
app.use(cookieParser);
// and modify and move your import
require("./routes/index")(app, passport);
Use Express router: Change your index.js like
// note your exports it's not a function, you're exporting this **router** object -> router = express.Router(),
module.exports = router;
//------------------------------------//
//***------------ROUTES------------***//
//------------------------------------//
router.get("/", function(req, res) {
res.render("landing");
});
router.get("/register", auth.optional, function(req, res) {
res.render("register");
});
...
And change your import to:
var indexRoutes = require("./routes/index");

Categories