如何解决Node.js:使用 express 访问 HTTP POST 请求的 JSON 正文
我正在向我的 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 得到“undefined”。我尝试使用:
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify({
url: "https://www.nothing.com",name: "hello"
})
而不是直接在请求选项中使用json,但无济于事。我什至按照某人的建议尝试使用 app.use(express.json());
。
有什么问题?
解决方法
显然我处理 post 请求的方式不正确,我不得不用 req.write() 在单独的一行中发送正文,如下所示:
const http = require('http');
const data = JSON.stringify({ //<--- data to send as body
url: "https://www.nothing.com",name: "hello"
});
const req = http.request({
hostname: '127.0.0.1',port: 3000,path: '/test',method: 'POST',headers: {
'Content-Type': 'application/json'
}
},res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data',d => {
process.stdout.write(d);
})
})
req.on('error',error => {
console.error(error);
})
req.write(data); //<--- this line
req.end();
,
你必须添加 body-parser 中间件 http://expressjs.com/en/resources/middleware/body-parser.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。