Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

node.js - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...