请求体为空express js

3

我已经花费了数小时来尝试弄清楚为什么req.body为空。我在stackoverflow上到处查找并尝试了所有方法,但没有运气。

我尝试设置:

app.use(bodyParser.urlencoded({extended: false})); //false

但这并没有改变任何事情。

这是app.js文件。

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var ajax = require('./routes/ajax');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.disable('etag'); //disable cache control

app.use('/', index);
app.use('/ajax', ajax);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

现在让我们来看一下 ajax.js。
var express = require('express');
var router = express.Router();
router.post('/1/kyc/form', function (req, res, next) {
    console.log(req.body) //prints {}
});

以下是客户端发送的请求:

enter image description here

1个回答

8
您的请求中的Content-Type头部无效:
Content-Type: application/json;

结尾的分号不应该出现在那里。因此应该是这样的:
Content-Type: application/json

值得一提的是,这里并没有使用 bodyParser.urlencoded;因为请求体内容为 JSON 格式,所以使用的是 bodyParser.json 处理请求体。不过,两种类型的解析器同时使用也是完全没有问题的。

编辑:如果客户端发送的内容超出您的控制范围(或者在客户端进行修复太麻烦),您可以向 Express 添加额外的中间件来修复无效的头部信息:

app.use(function(req, res, next) {
  if (req.headers['content-type'] === 'application/json;') {
    req.headers['content-type'] = 'application/json';
  }
  next();
});

请确保在加载 bodyParser.json 的代码行之前执行此操作。


我该如何通知 Express.js 将 application/json; 视为 application/json 的相同内容呢?(我知道更容易修复客户端请求,但我想知道这个问题是否可以从后端解决?) - TSR
1
谢谢,这对我有用!我通过Fiddler检查了请求并提取了MIME类型。然后我将该MIME类型放入条件语句中。if (req.headers["content-type"] === "text/plain;charset=UTF-8") { 现在我终于可以解析请求正文了。 - gdyrrahitis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接