【发布时间】:2017-08-26 08:48:37
【问题描述】:
我正在将一些数据从我的 ReactJS 客户端发布到 Express 服务器,但似乎我无法访问 req.body 中的数据...。我正在以这种方式发送 JSON 对象:
var url = 'http://localhost:8000/scrape/';
const {main} = getState()
const info = { name : main.title, items : main.list}
var options = {
url: url,
method: 'POST',
body : JSON.stringify(info),
json: true,
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
Request(options, (error, response, data) => {
// !error ? dispatch( setSearchResults(JSON.parse(data) ) ) : dispatch( setError(error) );
});
当我在 Express 中使用 console.log(req.body) 时,我收到:
{ '{"name":"test","items":': { '{"url":"test","code":"ING"},{"url":"test","code":"KIN"},{"url":"test","code":"GAO"}': '' } }
在我的 Express 中,我使用 bodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
我尝试使用 JSON.stringify(req.body) 和 JSON.parse(req.body) 但都没有成功,有什么建议吗?
【问题讨论】:
-
为什么将
Content-Type设为application/x-www-form-urlencoded而POST 正文是JSON? -
是的,我注意到当我查看代码时,似乎当我尝试 application/json 时,req.body 将在 Express 中保持为空
-
代码中的
Request模块是什么?另外,您是否检查过浏览器开发工具中的 HTTP 网络——当Content-Type为application/json时,客户端发送的 JSON 正文是? -
Request is this libary npmjs.com/package/request ,当 Content-Type 为 application/json 时,请求将作为 OPTIONS 请求发送,甚至不会到达我的快递服务器
-
正文解析器不链接,每个请求只能运行一个。在这种情况下,似乎
urlencoded开始并解析了作为字符串的主体,所以我猜req.body是一个字符串。底线:使用 JSON 内容类型