【问题标题】:Request body is empty in Express router middlewareExpress 路由器中间件中的请求正文为空
【发布时间】:2018-11-26 12:48:17
【问题描述】:

这是我使用 express 的简单 nodejs 应用:

const express = require('express');
const app = express();
const user = require('./routes/user').user;
const browser = require('./routes/browser');
const bodyParser = require('body-parser');

// CORS middleware
const allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Access-Control-Allow-Headers', '*');
    next();
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(allowCrossDomain);

app.use('/', user);
app.use('/', browser);

const port = process.env.PORT || 4001;

app.listen(port, function() {
    console.log('Express server listening on port ' + port)
});

路由处理程序“浏览器”,我在其中添加了中间件:

const express = require('express');
const router = express.Router();

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

router.post('/get-content', (req, res) => { 

});

Console

在这里,我遇到了中间件的奇怪行为。我想获取请求正文数据,但在控制台中我看到的是空对象,而不是带有内容的预期正文。在第二次调用 next() 中间件后,我终于得到了请求正文。帮助我了解我的中间件行为。

【问题讨论】:

  • 看起来第一个请求是CORS preflight request
  • 您使用哪个程序发送 POST 请求?
  • @David Vicente 使用 Axios 前端应用发送的 POST 请求
  • @robertklep 非常感谢,你帮了我很多。我必须通过 express 应用中间件处理 Preflight 请求。

标签: node.js express middleware


【解决方案1】:

可以帮上忙。安装 cors 包,并在 express.use 中提供。

https://www.npmjs.com/package/cors

【讨论】:

  • 非常感谢。使用这个包也解决了我的问题。
【解决方案2】:

支持 CORS 飞行前请求的中间件

const allowCrossDomain = function(req, res, next) { 
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Access-Control-Allow-Headers', '*');

    //intercepts OPTIONS method
    if ('OPTIONS' === req.method) {
        res.sendStatus(200);
      } else {
        next();
      }
}

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2021-11-27
    • 2019-10-24
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多