代码之家  ›  专栏  ›  技术社区  ›  Ron I

从Node/Express:OSError:Invalid chunk header发布到Python Flask服务器

  •  1
  • Ron I  · 技术社区  · 7 年前

    我试图将一些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();
    

    现在可以了!

    1 回复  |  直到 7 年前
        1
  •  1
  •   robertklep    7 年前

    当你使用 req.write() ,Node.js将默认使用 "chunked transfer encoding" 请求写入() 将向HTTP服务器发送一块数据,前面是字节数。

    要结束请求,需要显式调用 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"}));  
    
    推荐文章