Express.js req.body undefined

node.jsExpress

node.js Problem Overview


I have this as configuration of my Express server

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());

But still when I ask for req.body.something in my routes I get some error pointing out that body is undefined. Here is an example of a route that uses req.body :

app.post('/admin', function(req, res){
	console.log(req.body.name);
});

I read that this problem is caused by the lack of app.use(express.bodyParser()); but as you can see I call it before the routes.

Any clue?

node.js Solutions


Solution 1 - node.js

UPDATE July 2020

express.bodyParser() is no longer bundled as part of express. You need to install it separately before loading:

npm i body-parser

// then in your app
var express = require('express')
var bodyParser = require('body-parser')
 
var app = express()
 
// create application/json parser
var jsonParser = bodyParser.json()
 
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
 
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  res.send('welcome, ' + req.body.username)
})
 
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  // create user in req.body
})

See here for further info

original follows

You must make sure that you define all configurations BEFORE defining routes. If you do so, you can continue to use express.bodyParser().

An example is as follows:

var express = require('express'),
    app     = express(),
    port    = parseInt(process.env.PORT, 10) || 8080;

app.configure(function(){
  app.use(express.bodyParser());
});

app.listen(port);
    
app.post("/someRoute", function(req, res) {
  console.log(req.body);
  res.send({ status: 'SUCCESS' });
});

Solution 2 - node.js

Latest versions of Express (4.x) has unbundled the middleware from the core framework. If you need body parser, you need to install it separately

npm install body-parser --save

and then do this in your code

var bodyParser = require('body-parser')
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

Solution 3 - node.js

No. You need to use app.use(express.bodyParser()) before app.use(app.router). In fact, app.use(app.router) should be the last thing you call.

Solution 4 - node.js

Express 4, has build-in body parser. No need to install separate body-parser. So below will work:

export const app = express();
app.use(express.json());

Solution 5 - node.js

First make sure , you have installed npm module named 'body-parser' by calling :

npm install body-parser --save

Then make sure you have included following lines before calling routes

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

Solution 6 - node.js

As already posted under one comment, I solved it using

app.use(require('connect').bodyParser());

instead of

app.use(express.bodyParser());

I still don't know why the simple express.bodyParser() is not working...

Solution 7 - node.js

The Content-Type in request header is really important, especially when you post the data from curl or any other tools.

Make sure you're using some thing like application/x-www-form-urlencoded, application/json or others, it depends on your post data. Leave this field empty will confuse Express.

Solution 8 - node.js

Add in your app.js

before the call of the Router

const app = express();
app.use(express.json());

Solution 9 - node.js

app.use(express.json());

It will help to solve the issue of req.body undefined

Solution 10 - node.js

// Require body-parser (to receive post data from clients)

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json

app.use(bodyParser.json())

Solution 11 - node.js

The question is answered. But since it is quite generic and req.body undefined is a frequent error, especially for beginners, I find this is the best place to resume all that I know about the problem.


This error can be caused by the following reasons:

1. [SERVER side] [Quite often] Forget or misused parser middleware
  • You need to use appropriate middleware to parse the incoming requests. For example, express.json() parses request in JSON format, and express.urlencoded() parses request in urlencoded format.
const app = express();
app.use(express.urlencoded())
app.use(express.json())

You can see the full list in the express documentation page

  • You should use the parser middleware before the route declaration part (I did a test to confirm this!). The middleware can be configured right after the initialization express app.

  • Like other answers pointed out, bodyParser is deprecated since express 4.16.0, you should use built-in middlewares like above.

2. [CLIENT side] [Rarely] Forget to send the data along with the request
  • Well, you need to send the data...

To verify whether the data has been sent with the request or not, open the Network tabs in the browser's devtools and search for your request.

  • It's rare but I saw some people trying to send data in the GET request, for GET request req.body is undefined.
3. [SERVER & CLIENT] [Quite often] Using different Content-Type
  • Server and client need to use the same Content-Type to understand each other. If you send requests using json format, you need to use json() middleware. If you send a request using urlencoded format, you need to use urlencoded()...

  • There is 1 tricky case when you try to upload a file using the form-data format. For that, you can use multer, a middleware for handling multipart/form-data.

  • What if you don't control the client part? I had a problem when coding the API for Instant payment notification (IPN). The general rule is to try to get information on the client part: communicate with the frontend team, go to the payment documentation page... You might need to add appropriate middleware based on the Content-Type decided by the client part.

Finally, a piece of advice for full-stack developers :)

When having a problem like this, try to use some API test software like Postman. The object is to eliminate all the noise in the client part, this will help you correctly identify the problem.

In Postman, once you have a correct result, you can use the code generation tool in the software to have corresponded code. The button </> is on the right bar. You have a lot of options in popular languages/libraries... enter image description here

Solution 12 - node.js

Looks like the body-parser is no longer shipped with express. We may have to install it separately.

var express    = require('express')
var bodyParser = require('body-parser')
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!

Refer to the git page https://github.com/expressjs/body-parser for more info and examples.

Solution 13 - node.js

In case anyone runs into the same issue I was having; I am using a url prefix like

http://example.com/api/

which was setup with router

app.use('/api', router); 

and then I had the following

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

What fixed my issue was placing the bodyparser configuration above app.use('/api', router);

Final

// setup bodyparser
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

//this is a fix for the prefix of example.com/api/ so we dont need to code the prefix in every route
    app.use('/api', router); 

Solution 14 - node.js

Most of the time req.body is undefined due to missing JSON parser

const express = require('express');
app.use(express.json());

could be missing for the body-parser

const bodyParser  = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

and sometimes it's undefined due to cros origin so add them

const cors = require('cors');
app.use(cors())

Solution 15 - node.js

The middleware is always used as first.

//MIDDLEWARE
app.use(bodyParser.json());
app.use(cors());    
app.use(cookieParser());

before the routes.

//MY ROUTES
app.use("/api", authRoutes);

Solution 16 - node.js

express.bodyParser() needs to be told what type of content it is that it's parsing. Therefore, you need to make sure that when you're executing a POST request, that you're including the "Content-Type" header. Otherwise, bodyParser may not know what to do with the body of your POST request.

If you're using curl to execute a POST request containing some JSON object in the body, it would look something like this:

curl -X POST -H "Content-Type: application/json" -d @your_json_file http://localhost:xxxx/someRoute

If using another method, just be sure to set that header field using whatever convention is appropriate.

Solution 17 - node.js

Use app.use(bodyparser.json()); before routing. // . app.use("/api", routes);

Solution 18 - node.js

You can try adding this line of code at the top, (after your require statements):

app.use(bodyParser.urlencoded({extended: true}));

As for the reasons as to why it works, check out the docs: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions

Solution 19 - node.js

in Express 4, it's really simple

const app = express()
const p = process.env.PORT || 8082

app.use(express.json()) 

Solution 20 - node.js

History:

Earlier versions of Express used to have a lot of middleware bundled with it. bodyParser was one of the middleware that came with it. When Express 4.0 was released they decided to remove the bundled middleware from Express and make them separate packages instead. The syntax then changed from app.use(express.json()) to app.use(bodyParser.json()) after installing the bodyParser module.

bodyParser was added back to Express in release 4.16.0, because people wanted it bundled with Express like before. That means you don't have to use bodyParser.json() anymore if you are on the latest release. You can use express.json() instead.

The release history for 4.16.0 is here for those who are interested, and the pull request is here.

Okay, back to the point,

Implementation:

All you need to add is just add,

app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(app.router); // Route will be at the end of parser

And remove bodyParser (in newer version of express it is not needed)

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

And Express will take care of your request. :)

Full example will looks like,

const express       = require('express')
const app           = express()

app.use(express.json())
app.use(express.urlencoded({ extended: true}));

app.post('/test-url', (req, res) => {
    console.log(req.body)
    return res.send("went well")
})

app.listen(3000, () => {
    console.log("running on port 3000")
})

Solution 21 - node.js

This occured to me today. None of above solutions work for me. But a little googling helped me to solve this issue. I'm coding for wechat 3rd party server.

Things get slightly more complicated when your node.js application requires reading streaming POST data, such as a request from a REST client. In this case, the request's property "readable" will be set to true and the POST data must be read in chunks in order to collect all content.

http://www.primaryobjects.com/CMS/Article144

Solution 22 - node.js

Wasted a lot of time:

Depending on Content-Type in your client request
the server should have different, one of the below app.use():

app.use(bodyParser.text({ type: 'text/html' }))
app.use(bodyParser.text({ type: 'text/xml' }))
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
app.use(bodyParser.json({ type: 'application/*+json' }))

Source: https://www.npmjs.com/package/body-parser#bodyparsertextoptions

Example:

For me, On Client side, I had below header:

Content-Type: "text/xml"

So, on the server side, I used:

app.use(bodyParser.text({type: 'text/xml'}));

Then, req.body worked fine.

Solution 23 - node.js

To work, you need to app.use(app.router) after app.use(express.bodyParser()), like that:

app.use(express.bodyParser())
   .use(express.methodOverride())
   .use(app.router);



Solution 24 - node.js

var bodyParser = require('body-parser');
app.use(bodyParser.json());

This saved my day.

Solution 25 - node.js

I solved it with:

app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
});

Solution 26 - node.js

In my case, it was because of using body-parser after including the routes.

The correct code should be

app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(indexRoutes);
app.use(userRoutes);
app.use(adminRoutes);

Solution 27 - node.js

If you are using some external tool to make the request, make sure to add the header:

Content-Type: application/json

Solution 28 - node.js

This is also one possibility: Make Sure that you should write this code before the route in your app.js(or index.js) file.

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Solution 29 - node.js

This issue may be because you have not use body-parser (link)

var express = require('express');
var bodyParser  = require('body-parser');

var app = express();
app.use(bodyParser.json());

Solution 30 - node.js

When I use bodyParser it is marked as deprecated. To avoid this I use the following code with express instead of bodyParser.

Notice: the routes must declared finally this is important! Other answers here described the problem well.

const express = require("express");
const app = express();

const routes = require('./routes/api');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Routes must declared finally
app.use('/', routes);

Solution 31 - node.js

You can use express body parser.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

Solution 32 - node.js

Latest version of Express already has body-parser built-in. So you can use:

const express = require('express);
... 
app.use(express.urlencoded({ extended: false }))
.use(express.json());

Solution 33 - node.js

Mine was a text input and I'm adding this answer here regardless so it would help people. Make sure your encoding is set when parsing! I struggled to make it work until I set a proper value to it.

This was the error I was getting without using any parser:

error info: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.

Received an instance of undefined at Function.from (buffer.js:327:9)

We do not have to use body-parser now in Express as others have already mentioned, but just that app.use(express.text()); did not solve my issue.

undefined now changed to Object. According to Express documentation, request body returns an empty object ({}) if Content-Type doesn't match (among others).

error info: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.

Received an instance of Object at Function.from (buffer.js:327:9)

The encoding type you set needs to be on point as well. In my case, it was text/plain. You can change it to suit your needs like JSON, etc. I did this and voila! Worked like a charm!

app.use(express.text({
	type: "text/plain" 
}));

Solution 34 - node.js

In express 4 and above you don't need body parser they have their own json parse method, At the higehset level of your express app add

var express = require('express');
var app = express()
app.use(express.json()); //declare this to receive json objects.

Other answers failed to mention, when making the request to express via fetch or other clients. The request must be formatted a certain way.

const response = await fetch(`${expressAddress}/controller/route`, { 
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      headers: {
          'Content-Type': 'application/json' //this must be set to a json type
      },
      body: JSON.stringify(row) //regular js object need to be converted to json
  })

If you make the fetch request like this the req.body will output your json object as expected.

Solution 35 - node.js

In case if you post SOAP message you need to use raw body parser:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.raw({ type: 'text/xml' }));

Solution 36 - node.js

Building on @kevin-xue said, the content type needs to be declared. In my instance, this was only occurring with IE9 because the XDomainRequest doesn't set a content-type, so bodyparser and expressjs were ignoring the body of the request.

I got around this by setting the content-type explicitly before passing the request through to body parser, like so:

app.use(function(req, res, next) {
    // IE9 doesn't set headers for cross-domain ajax requests
    if(typeof(req.headers['content-type']) === 'undefined'){
        req.headers['content-type'] = "application/json; charset=UTF-8";
    }
    next();
})
.use(bodyParser.json());

Solution 37 - node.js

Credit to @spikeyang for the great answer (provided below). After reading the suggested article attached to the post, I decided to share my solution.

When to use?

The solution required you to use the express router in order to enjoy it.. so: If you have you tried to use the accepted answer with no luck, just use copy-and-paste this function:

function bodyParse(req, ready, fail) 
{
    var length = req.header('Content-Length');

    if (!req.readable) return fail('failed to read request');

    if (!length) return fail('request must include a valid `Content-Length` header');

    if (length > 1000) return fail('this request is too big'); // you can replace 1000 with any other value as desired

    var body = ''; // for large payloads - please use an array buffer (see note below)

    req.on('data', function (data) 
    {
        body += data; 
    });

    req.on('end', function () 
    {
        ready(body);
    });
}

and call it like:

bodyParse(req, function success(body)
{

}, function error(message)
{

});

NOTE: For large payloads - please use an array buffer (more @ MDN)

Solution 38 - node.js

For anyone who none of the answers above have worked for I had to enable cors between my front-end and express.

You can do this either by:

  1. Downloading and turning on a CORS extension for your browser, such as:

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

for Chrome,   

or by

  1. Adding the lines

     var cors=require('cors');
    
     app.use(cors());
    

to your express app.js page. (After npm install cors)

Solution 39 - node.js

Another possible way to get empty request.body when you forget the name attribute from the input element...

<input type="text" /> /* give back empty request.body -> {}*/
<input type="text" name="username" /> /* give back request.body -> {"username": "your-input"} */

Solution 40 - node.js

Simple example to get through all:

Express Code For Method='post' after Login:

This would not require any such bodyParser().

enter image description here

app.js

const express = require('express');
const mongoose = require('mongoose');
const mongoDB = require('mongodb');

const app = express();

app.set('view engine', 'ejs');

app.get('/admin', (req,res) => {
 res.render('admin');
});

app.post('/admin', (req,res) => {
 console.log(JSON.stringify(req.body.name));
 res.send(JSON.stringify(req.body.name));
});

app.listen(3000, () => {
 console.log('listening on 3000');
});

admin.ejs

<!DOCTYPE Html>
<html>
 <head>
  <title>Admin Login</title>
 </head>
 <body>
   <div>
    <center padding="100px">
       <form method="post" action="/admin">
          <div> Secret Key:
            <input name='name'></input>
          </div><br></br><br></br>
          <div>
            <button type="submit" onClick='smsAPI()'>Get OTP</button>
          </div>
       </form>
    </center>
    </div >
</body>
</html>

You get input. The 'name' in "" is a variable that carries data through method='post'. For multiple data input, name='name[]'.

Hence,

on name='name' 

input: Adu
backend: "Adu"

OR

input: Adu, Luv,
backend: "Adu, Luv,"

on

name='name[]'
input: Adu,45689, ugghb, Luv
backend: ["Adu,45689, ugghb, Luv"]

Solution 41 - node.js

Use this line for appropriate parsing at the top before any get or post request is made:

app.use(express.json()) 

This parses json data to Javascript Objects.

Solution 42 - node.js

As I get the same problem, although I know BodyParser is no longer used and I already used the app.use(express.json()) the problem was {FOR ME}: I was placing

app.use(express.json())

after

app.use('api/v1/example', example) => { concerns the route }

once I reorder those two lines;

1 - app.use(express.json())

2 - app.use('api/v1/example', example)

It worked now perfectly

Solution 43 - node.js

adding express.urlencoded({ extended: true }) to the route solves the problem.

router.post('/save',express.urlencoded({ extended: true }),  "your route");

Solution 44 - node.js

You have to check following things for that:-
1. app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
Implement body parser in your app.

2. Check headers in postman its should be based on your rest api's, like if your Content-Type: application/json it should be defined in your postman headers.

Solution 45 - node.js

You have missed

var bodyParser = require('body-parser')
var jsonParser = bodyParser.json()

//...

ourApp.post('/answer', jsonParser, function(req, res) {
//...

Solution 46 - node.js

What I did in my case is that I declared app.use(express.json()); app.use(express.urlencoded({ extended: false })); before my routes, and the issue got solved. I hope this helps you too!

Solution 47 - node.js

Firsl of all, ensure you are applying this middleware (express.urlencoded) before routes.

let app = express();

//response as Json
app.use(express.json()); 

//Parse x-www-form-urlencoded request into req.body
app.use(express.urlencoded({ extended: true }));     

app.post('/test',(req,res)=>{
    res.json(req.body);
});

The code express.urlencoded({extended:true}) only responds to x-www-form-urlencoded posts requests, so in your ajax/XMLHttpRequest/fetch, make sure you are sending the request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); header.

Thats it !

Solution 48 - node.js

Okay This may sound Dumb but it worked for me.

as a total beginner, I didn't realized that writing:

router.post("/", (res, req) => {
  console.log(req.body);
  req.send("User Route");
});

is wrong !

You have make sure that you pass parameters(req,res) of post/get in right order: and call them accordingly:

router.post("/", (req, res) => {
  console.log(req.body);
  res.send("User Route");
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMasiarView Question on Stackoverflow
Solution 1 - node.jsMark BonanoView Answer on Stackoverflow
Solution 2 - node.jsJayView Answer on Stackoverflow
Solution 3 - node.jsdanmactoughView Answer on Stackoverflow
Solution 4 - node.jsTechTurtleView Answer on Stackoverflow
Solution 5 - node.jsAnkit kaushikView Answer on Stackoverflow
Solution 6 - node.jsMasiarView Answer on Stackoverflow
Solution 7 - node.jsKevin XueView Answer on Stackoverflow
Solution 8 - node.jsabdesselamView Answer on Stackoverflow
Solution 9 - node.jsPrashanth KView Answer on Stackoverflow
Solution 10 - node.jsASHISH RView Answer on Stackoverflow
Solution 11 - node.jsĐăng Khoa ĐinhView Answer on Stackoverflow
Solution 12 - node.jsPraneeshView Answer on Stackoverflow
Solution 13 - node.jsJeff BeagleyView Answer on Stackoverflow
Solution 14 - node.jsANIK ISLAM SHOJIBView Answer on Stackoverflow
Solution 15 - node.jsSonali MangrindaView Answer on Stackoverflow
Solution 16 - node.jsab107View Answer on Stackoverflow
Solution 17 - node.jsuser1614168View Answer on Stackoverflow
Solution 18 - node.jsAnthony CantellanoView Answer on Stackoverflow
Solution 19 - node.jsGerardo BautistaView Answer on Stackoverflow
Solution 20 - node.jsMayurView Answer on Stackoverflow
Solution 21 - node.jsspikeyangView Answer on Stackoverflow
Solution 22 - node.jsManohar Reddy PoreddyView Answer on Stackoverflow
Solution 23 - node.jsHenioJRView Answer on Stackoverflow
Solution 24 - node.jsisdotView Answer on Stackoverflow
Solution 25 - node.jsKkkk KkkkView Answer on Stackoverflow
Solution 26 - node.jsRushikesh ShelkeView Answer on Stackoverflow
Solution 27 - node.jsInc33View Answer on Stackoverflow
Solution 28 - node.jsInamur RahmanView Answer on Stackoverflow
Solution 29 - node.jsArindamView Answer on Stackoverflow
Solution 30 - node.jsMarciView Answer on Stackoverflow
Solution 31 - node.jsKuldeep MishraView Answer on Stackoverflow
Solution 32 - node.jsLEMUEL ADANEView Answer on Stackoverflow
Solution 33 - node.jsSaranView Answer on Stackoverflow
Solution 34 - node.jsGreggory WileyView Answer on Stackoverflow
Solution 35 - node.jsopewixView Answer on Stackoverflow
Solution 36 - node.jspurpletonicView Answer on Stackoverflow
Solution 37 - node.jsymzView Answer on Stackoverflow
Solution 38 - node.jslmbView Answer on Stackoverflow
Solution 39 - node.jslendooView Answer on Stackoverflow
Solution 40 - node.jsAnk_247shbmView Answer on Stackoverflow
Solution 41 - node.jsVatsal A MehtaView Answer on Stackoverflow
Solution 42 - node.jsHicham MounadiView Answer on Stackoverflow
Solution 43 - node.jsBadr BellajView Answer on Stackoverflow
Solution 44 - node.jsANKIT MISHRAView Answer on Stackoverflow
Solution 45 - node.jsAmadeusz BlanikView Answer on Stackoverflow
Solution 46 - node.jsRupesh Chandra MohantyView Answer on Stackoverflow
Solution 47 - node.jsRafael Fernando FiedlerView Answer on Stackoverflow
Solution 48 - node.jsSohaib AhmadView Answer on Stackoverflow