gpt4 book ai didi

node.js - 从 Node/Express : OSError: Invalid chunk header POST 到 Python Flask 服务器

转载 作者:行者123 更新时间:2023-12-01 08:55:42 25 4
gpt4 key购买 nike

我试图将一些 json 发布到 python Flask 服务器,但收到以下错误:

OSError: Invalid chunk header

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"}

简单的获取请求有效

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 将默认使用 "chunked transfer encoding" ,这意味着每次调用 req.write() 都会向 HTTP 服务器发送一 block 数据,前面有一个字节计数。

我的猜测是 Werkzeug 超时了,因为你没有结束请求(所以 Werkzeug 期待一个新的 block ,或者一个请求结束,但没有得到它,并且在某些时候它会抛出一个错误)。

要结束请求,您需要在完成后显式调用 req.end():

let req = this.generatePostRequest(apiParams);
req.write(JSON.stringify({text:"this is only a test"}));
req.end();

或者,如果您要发送固定数量的数据,则可以组合 req.writereq.end:

let req = this.generatePostRequest(apiParams);
req.end(JSON.stringify({text:"this is only a test"}));

关于node.js - 从 Node/Express : OSError: Invalid chunk header POST 到 Python Flask 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52784608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com