从Node/Express发送到Python Flask服务器:OSError:Invalid chunk head

2024-10-01 15:39:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

OSError: Invalid chunk header

标题参数

^{pr2}$

post请求:

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

简单的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();

它现在起作用了!在


Tags: logjsonhttpdatareturnrequestfunctionres
1条回答
网友
1楼 · 发布于 2024-10-01 15:39:11

使用req.write()时,节点.js将默认使用"chunked transfer encoding",这意味着对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和{}:

^{pr2}$

相关问题 更多 >

    热门问题