【发布时间】:2021-01-11 17:57:27
【问题描述】:
我正在向我的 Express Web 服务器发送一个 http post 请求,将虚拟数据作为 json 发送。它正确接收请求并可以发回一个 json 对象,但由于某种原因它无法访问 post 请求正文。
我正在使用此代码进行快递:
const express = require('express');
const app = express();
const port = 3000;
app.post('/test', (req, res) => {
console.log(req.body);
res.json({"some": "thing"});
});
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`)
});
这是请求的代码:
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/test',
method: 'POST',
json: {
url: "https://www.nothing.com",
name: "hello"
}
}, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.end()
如您所见,我在本地运行它。客户端收到状态码 200 和服务器发送的 json {"some": "thing"},但服务器从 req.body 获取“未定义”。我尝试使用:
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify({
url: "https://www.nothing.com",
name: "hello"
})
直接在请求选项中代替json,但无济于事。我什至按照某人的建议尝试使用app.use(express.json());。
有什么问题?
【问题讨论】:
-
请添加此行 req.write(data);之前 req.end();
标签: node.js json express http-post