node js post request.body undefined

时间:2016-05-13 06:08:34

标签: javascript node.js

server.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');
var router = require('./router/main')(app, fs);

var server = app.listen(3000, function(){
  console.log('Express server has started on port 3000');
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

路由器/ main.js

module.exports = function(app, fs)
{
  app.post('/addUser/', function(req, res){
        console.log(req.body);
    });
}

我使用邮差工具!! requets param {"密码" :"传递","名称" :" dltlsdn"}

但是...... req.body没有发现....为什么...... ??

1 个答案:

答案 0 :(得分:3)

重新排序app.use语句。之前您在通过正文解析器之前处理了请求。

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');

//body parser before routes
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

var router = require('./router/main')(app, fs);

var server = app.listen(3000, function(){
   console.log('Express server has started on port 3000');
});

希望它对你有所帮助。