使用 Express 4 在 Node.js 中解析 JSON 发布请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23365344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing JSON post requests in Node.js with Express 4
提问by Jacob Horbulyk
I'm trying to write a simple Express applicaiton that recieves JSON in a Post request. Here is what I have so far on the server:
我正在尝试编写一个简单的 Express 应用程序,它在 Post 请求中接收 JSON。这是我到目前为止在服务器上的内容:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/acceptContacts', function(req, res) {
'use strict';
console.log(req.body);
console.log(req.body.hello);
res.send(200);
});
app.listen(8080);
And here is what I have on the client in the browser:
这是我在浏览器中的客户端上的内容:
var req = new XMLHttpRequest();
req.open('POST', 'http://localhost:8080/acceptContacts?Content-Type=application/json');
var obj = {hello:'world'};
req.send(JSON.stringify(obj))
However, I recieve the following output on the server's console:
但是,我在服务器的控制台上收到以下输出:
{}
undefined
Can anyone suggest the cause?
任何人都可以提出原因吗?
回答by MikeSmithDev
It will work if you use setRequestHeader:
如果您使用,它将起作用setRequestHeader:
var req = new XMLHttpRequest();
req.open('POST', 'http://localhost:8080/acceptContacts');
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var obj = {hello:'world'};
req.send(JSON.stringify(obj));

