我试图将一些json发布到python flask服务器,但出现以下错误:
OSError: Invalid chunk header
let apiParams = {
host: "0.0.0.0",
port: "5000",
path: "/",
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
generatePostRequest(apiParams) {
let req = http.request(apiParams, function (res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (body) {
console.log('Body: ' + body);
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
});
return req;
}
let req = this.generatePostRequest(apiParams);
req.write(JSON.stringify({text:"this is only a test"}));
console.log输出
Headers: {"content-type":"application/json","content-length":"37","server":"Werkzeug/0.14.1 Python/3.7.0","date":"Fri, 12 Oct 2018 17:46:23 GMT"}
Body: {"message": "Internal Server Error"}
简单的get请求有效
getRequest() {
let res = fetch('http://0.0.0.0:5000')
.then((response) => {
return response.json();
})
.then(function(data){
console.log(data);
return data;
})
.catch(function(e) {
console.log(e);
});
return res;
}
根据以下评论中的建议(谢谢@robertklep),我更新了以下内容:
let req = this.generatePostRequest(apiParams);
req.write(json);
req.end();
现在可以了!