我正在尝试将一些json发布到python烧瓶服务器,但收到以下错误:
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"}));
控制台.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"}
简单的获取请求工作
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;
}
当你使用req.write()
时,Node.js 将默认使用"分块传输编码",这意味着每次调用req.write()
都会向 HTTP 服务器发送一大块数据,前面有一个字节计数。
我的猜测是 Werkzeug超时了,因为你没有结束请求(所以 Werkzeug 期待一个新的块,或者一个请求结束,但没有得到它,并且在某个时候它会抛出错误(。
若要结束请求,需要在完成后显式调用req.end()
:
let req = this.generatePostRequest(apiParams);
req.write(JSON.stringify({text:"this is only a test"}));
req.end();
或者,如果您要发送固定数量的数据,则可以将req.write
和req.end
结合起来:
let req = this.generatePostRequest(apiParams);
req.end(JSON.stringify({text:"this is only a test"}));