Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force parse request body as plain text instead of json in Express?

I am using nodejs + Express (v3) like this:

app.use(express.bodyParser()); app.route('/some/route', function(req, res) {   var text = req.body; // I expect text to be a string but it is a JSON }); 

I checked the request headers and the content-type is missing. Even if "Content-Type" is "text/plain" it is parsing as a JSON it seems. Is there anyway to tell the middleware to always parse the body as a plain text string instead of json? Earlier versions of req used to have req.rawBody that would get around this issue but now it does not anymore. What is the easiest way to force parse body as plain text/string in Express?

like image 426
pathikrit Avatar asked Sep 10 '12 03:09

pathikrit


People also ask

How do I send a plain text request body?

String text = "plain text request body"; RequestBody body = RequestBody. create(MediaType. parse("text/plain"), text); Call<ResponseBody> call = service. getStringRequestBody(body); Response<ResponseBody> response = call.

What can I use instead of body parser in Express?

node. js - Non-deprecated alternative to body-parser in Express.

Does Express automatically parse JSON?

Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4. 16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.

Do you still need body parser with Express?

No need to install body-parser with express , but you have to use it if you will receive post request.


1 Answers

In express 4.x you can use the text parser from bodyParser https://www.npmjs.org/package/body-parser

just add in app.js

app.use(bodyParser.text()); 

Also in the desired route

router.all('/',function(req,res){     console.log(req.body);  }) 
like image 106
Nacho Avatar answered Sep 24 '22 15:09

Nacho