Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty req.body receiving text/plain POST request to node.js

Tags:

http

post

node.js

Why can't I receive plain text sent in a POST request body?

The request made from a client browser:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/MyRoute/MySubRoute");
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xhr.send("hello!");    

Using Express with my node server:

app.post('/MyRoute/MySubRoute', function(req, res) {
    console.log("Received:"+require('util').inspect(req.body,{depth:null});
    res.send();
});

Logged to the console I get:

Received:{}

I've tried with text/plain (no charset), with the same result. If I change my content type to application/json and pass a simple JSON string it works fine.

like image 810
pancake Avatar asked Jul 22 '13 17:07

pancake


2 Answers

Summarising the above comments which answer the question:

  • The client's XMLHttpRequest is correct
  • On the server side, Express uses connect's bodyParser which by default only supports the following content types:
    • application/json
    • application/x-www-form-urlencoded
    • multipart/form-data
  • Because the content-type of text/plain is not implemented by Express, there is no method to wait for the body to be received before calling the app/post route.
  • The solution is to add the text/plain content type to Express as described here
like image 196
pancake Avatar answered Nov 13 '22 02:11

pancake


Add

app.use(express.text())

You can read more about it here

like image 37
Aditya Singla Avatar answered Nov 13 '22 01:11

Aditya Singla