[英]Express keeps getting request.body as undefined JSON object
I am making an Ajax request that looks like this: 我正在制作一个如下所示的Ajax请求:
$.ajax({
url: '/gen',
type: 'POST',
data: JSON.stringify({'one': 1, 'two':2}),
success: function(data) {console.log(this)}
});
and my express portion looks like this: 我的快递部分看起来像这样:
var express = require('express');
var app = express();
var router = express.Router();
app.set('port', (process.env.PORT || 5000));
router.post('/gen', function(req, res) {
console.log(req.body);
});
this always outputs undefined
in the console. 这总是在控制台中输出undefined
。
How can I change this around to make the req.body, or any part of the req, contain the information I am trying to send over to the express portion of the code. 如何更改此权限以使req.body或req的任何部分包含我尝试发送到代码的快速部分的信息。
You need to use the body parser. 您需要使用正文解析器。
var bodyParser = require('body-parser')
app.use(bodyParser.json());
See: 看到:
You may also need to add: 您可能还需要添加:
contentType: 'application/json',
in your .ajax()
options. 在.ajax()
选项中。
To use use req.body
you have to use the bodyParser
middleware, import it like this: 要使用req.body
你必须使用bodyParser
中间件,像这样导入:
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
router.post('/gen', function(req, res) {
console.log(req.body);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.