简体   繁体   中英

request.body is empty in node.js, express and body parser

I am trying to "post" a request to my node server.

Following is the xhttp request.

let parcel = {
  userId: userId, //string
  unitid: unitid, //string
  selections: selections //array
};

 //Call to the Server
 var oReq = new XMLHttpRequest();
 oReq.addEventListener("load", transferComplete);

 oReq.open("GET", "http://node.server.com/interaction", true);
 //oReq.setRequestHeader('Content-Type', 'application/json');
 oReq.send(parcel);

 function transferComplete(evt) {
     console.log(this.responseText);
 }

Here is the server code

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

let app = express();

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

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

app.use('/interaction', interaction);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.set("port", process.env.PORT || 5000);

var server = app.listen(app.get('port'), () => {
  console.log("server is started");
});

And the interaction router

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  console.log(req.body)
  res.send(req.body);
});

module.exports = router;

The request receives a response but the console.log(req.body) returns an empty object. I have even checked the "req" object. The body node in that object is empty too. Where am i going wrong. Where can i receive my parcel object in server?

You are not sending any body in the client side so it is not surprising that you are not receiving it on the server.

You're making a GET request that doesn't have a body by definition.

Try using curl to make a request with a body and see if you get in on the server - that way you should eliminate the possibility that it's a problem with Express or body-parser. Make sure you use a correct content-type.

If you want to send a body then:

  1. use an HTTP method that supports it in your route handler (like POST)
  2. use the same HTTP method on the client side
  3. actually send something as a body correctly

If you have trouble using the XMLHttpRequest directly (which has a terrible API) then use something like jQuery, browser-request, SuperAgent, Axios, Got, Request, Reqwest etc.:

Also to debug the data that was actually sent in the request, see the Network tab in your browser's developer tools and to have a really good insight about what's going on, use netcat:

$ nc -lp 3333

It listens on port 3333 (in this case) and will print the entire request with all headers and body. For example accessing http://localhost:3333/xxx in the browser might print:

GET /xxx HTTP/1.1
Host: localhost:3333
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/59.0.3071.109 Chrome/59.0.3071.109 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,pl;q=0.6
Cookie: io=HQz0J7NwYj76pKf_AAAD

Note that it will not return a response by itself and it will work for a single request only so you'll need to restart your netcat command to test it again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM