【问题标题】:Cannot access to req.body inside middlewares无法访问中间件中的 req.body
【发布时间】:2016-03-31 23:41:18
【问题描述】:

我实际上在 node.js 中有一个非常小的应用程序,带有 Express,我无法访问 req.body。

这是我的app.js 代码:

var express = require('express'),
    middleware = require('./middleware'),
    mysql  = require('mysql'),
    app = express();

app.use(middleware.authenticate);
app.use(middleware.getScope);

app.listen(3000);
module.exports = app;

以及带有中间件的文件:

var bcrypt = require('bcrypt'),
    mysql  = require('mysql');

function authenticate(req, res, next){
   console.log(req.body);
    next();
}

function getScope(req, res, next){
    console.log(req.body);
    next();
}

module.exports.authenticate = authenticate;
module.exports.getScope = getScope;

在所有情况下 req.body 都是undefined

我正在使用x-www-form-urlencoded 协议发送数据 throw Postman,在这种情况下是必须的。

谢谢!!

【问题讨论】:

标签: node.js rest express


【解决方案1】:

需要加body-parser表达:

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

在此处查看请求 http://expressjs.com/en/api.html

也许 POST 路由也可以提供帮助:

app.post('/', function (req, res, next) {
  console.log(req.body);
  res.json(req.body);
});

【讨论】:

    猜你喜欢
    • 2023-02-03
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2021-07-02
    相关资源
    最近更新 更多