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

后端 未结 8 2126
死守一世寂寞
死守一世寂寞 2021-01-03 17:49

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         


        
8条回答
  •  [愿得一人]
    2021-01-03 18:27

    If you remove the use of the bodyParser() middleware, it should be text. You can view the bodyParser docs for more info: http://www.senchalabs.org/connect/middleware-bodyParser.html

    Remove this line:

    app.use(express.bodyParser());
    

    EDIT:

    Looks like you're right. You can create your own rawBody middleware in the meantime. However, you still need to disable the bodyParser(). Note: req.body will still be undefined.

    Here is a demo:

    app.js

    var express = require('express')
      , http = require('http')
      , path = require('path')
      , util = require('util');
    
    var app = express();
    
    function rawBody(req, res, next) {
      req.setEncoding('utf8');
      req.rawBody = '';
      req.on('data', function(chunk) {
        req.rawBody += chunk;
      });
      req.on('end', function(){
        next();
      });
    }
    
    app.configure(function(){
      app.set('port', process.env.PORT || 3000);
      app.use(rawBody);
      //app.use(express.bodyParser());
      app.use(express.methodOverride());
      app.use(app.router);
    });
    
    app.post('/test', function(req, res) {
      console.log(req.is('text/*'));
      console.log(req.is('json'));
      console.log('RB: ' + req.rawBody);
      console.log('B: ' + JSON.stringify(req.body));
      res.send('got it');
    });
    
    http.createServer(app).listen(app.get('port'), function(){
      console.log("Express server listening on port " + app.get('port'));
    });
    

    test.js

    var request = require('request');
    
    request({
      method: 'POST',
      uri: 'http://localhost:3000/test',
      body: {'msg': 'secret'},
      json: true
    }, function (error, response, body) {
      console.log('code: '+ response.statusCode);
      console.log(body);
    })
    

    Hope this helps.

提交回复
热议问题