我收到此错误:
错误是:SyntaxError:意外的令牌'在位置0的JSON中 ' {用户名:XYZ,密码:XYZ}'
当我使用此命令呼叫服务器时:
{curl -H" Content-Type:application / json" -X POST -d' {"用户名":" xyz","密码":" xyz"}' http://localhost:8080
我的代码就是这样:
var http = require('http');
function handle_incoming_request(req,res) {
console.log("Incoming Request:("+ req.method + ")" + req.url);
var json_data = "";
req.on(
"readable",
function(){
var d = req.read();
if(typeof d == 'string')
json_data += d;
else if(typeof d == 'object' && d instanceof Buffer)
json_data += d.toString("utf8");
});
req.on(
"end",
function(){
var out = "";
if(!json_data)
out = "I am no JSON"
else {
var json;
try {
json = JSON.parse(json_data.toString("utf8"));
} catch (err) {
console.log("Error is:" + err + "\n" + json_data);
}
if(!json)
out = "Inavlid JSON" + json;
else
out = "Valid JSON" + json_data;
}
res.end(out);
}
);
}
var s = http.createServer(handle_incoming_request);
s.listen(8080);