我正在创建一个简单的 NodeJS 服务器,它将接收一个 POST 请求并执行一些业务逻辑
var server = http.createServer(function(request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
try {
var post = JSON.parse(body);
deal_with_post_data(request,post);
response.writeHead(200, {"Content-Type": "text/plain"});
response.end();
return;
}catch (err){
response.writeHead(500, {"Content-Type": "text/plain"});
response.write("Bad Post Data. Is your data a proper JSON?\n");
response.end();
return;
}
});
}
});
server.listen(3000);
console.log("server started")
现在,当我使用 json 测试来自邮递员的示例 POST 请求时,出现错误Bad Post Data. Is your data a proper JSON?
,这基本上意味着它进入了500 internal server error
.
这是我尝试过的示例 JSON
{
"glossary":"book"
}
并将 POST 请求发送到 http://<IP_ADDRESS>:3000
任何人都可以请建议吗?
刚刚测试了你的代码:
const http = require('http');
var server = http.createServer(function(request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
try {
var post = JSON.parse(body);
// deal_with_post_data(request,post);
console.log(post); // <--- here I just output the parsed JSON
response.writeHead(200, {"Content-Type": "text/plain"});
response.end();
return;
}catch (err){
response.writeHead(500, {"Content-Type": "text/plain"});
response.write("Bad Post Data. Is your data a proper JSON?\n");
response.end();
return;
}
});
}
});
server.listen(3000);
console.log("server started")
在 Postman 中,我使用给定的 JSON (as raw
)发出 POST 请求,并在控制台上记录了正确的 JSON。所以提供的代码没问题。问题可能是deal_with_post_data
函数(您没有在此处显示)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句