Flask无法看到由Node发送的JSON数据

4

我正在尝试使用Node将JSON数据发送到Flask,但是Flask无法读取数据。我在Flask中尝试打印request.data,但没有输出任何内容。我还尝试打印request.json,但返回了一个400响应。为什么Flask看不到Node发送的JSON数据?

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def hello():
    if request.method == "POST":
        print "POST";
        print "get_json: ", request.get_json();
        # print "get_json: ", request.get_json(force = True);
        print "data: ", request.data;
        return 'POST';
    else:
        print "GET";
        return "GET";

if __name__ == "__main__":
    app.run()

var async = require('async'),
    http = require('http'),
    util = require('util');

var server = {
        hostname: '127.0.0.1',
        port: 5000
    };

function request(method, path, headers, body, callback) {
    var req = {};

    if(!headers) {
        headers = {};
    }

    headers['Content-Type'] = 'application/json';

    console.log(method + ' ' + path);
    console.log(' Req:');
    console.log('  headers: ' + JSON.stringify(headers));
    if(body) {
        console.log('  body   : ' + JSON.stringify(body));
    } else {
        console.log('  no body');
    }

    req = http.request({
            hostname: server.hostname,
            port: server.port,
            path: path,
            method: method,
            headers: headers
        }, (res) => {
            var resbody = '';

            res.on('data', (chunk) => {
                resbody = resbody + chunk;
            });

            res.on('end', () => {
                console.log(' Res:');
                console.log('  headers: ' + JSON.stringify(res.headers));
                if(body) {
                    console.log('  body   : ' + JSON.stringify(resbody));
                } else {
                    console.log('  no body');
                }               
                callback(resbody);
            });
        }
    );

    req.on('error', (err) => {
        console.log(method + ' ' + path + ' ERR: ' + util.inspect(err));
        callback(err);
    });

    if(body) {
        req.write(JSON.stringify(body));
    }

    req.end();
}

request('POST', '/', null, {foo: 'bar'}, (res) => {});

JavaScript输出的内容:

POST /
 Req:
  headers: {"Content-Type":"application/json"}
  body   : {"foo":"bar"}
 Res:
  headers: {"content-type":"text/html","content-length":"192","server":"Werkzeug/0.11.11 Python/2.7.11","date":"Fri, 09 Sep 2016 10:29:58 GMT"}
  body   : "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n<title>400 Bad Request</title>\n<h1>Bad Request</h1>\n<p>The browser (or proxy) sent a request that this server could not understand.</p>\n"

Python的输出:

POST
get_json: 127.0.0.1 - - [09/Sep/2016 12:29:58] "POST / HTTP/1.1" 400 -

更新了所有代码

curl:

> curl.exe 127.0.0.1:5000 --header "Content-Type: application/json" --data {\"foo\":\"bar\"}
POST

如果您使用http://httpbin.org/post,将收到一个JSON响应,该响应会回显您发送的内容;您将得到相同的结果(POST正文中未发送任何内容)。 - Martijn Pieters
啊,我看到它在哪里编写JSON格式的主体了。然而,我没有看到任何Content-Length头被设置;查看node.js http.request()文档,他们在代码中明确设置了该头。 - Martijn Pieters
@MartijnPieters:设置或不设置Content-Length都没有改变任何东西,你确定http://httpbin.org/post的URL吗?我收到了ADDRNOTFOUND - DrakaSAN
如果你使用cURL呢? - hjpotter92
@hjpotter92:与node.js版本相同的错误。但是POSTMan可以工作。 - DrakaSAN
@hjpotter92:好的,我刚才只是输入了错误的命令,curl确实可以工作,所以问题肯定出在我的node.js代码中。 - DrakaSAN
1个回答

1
Python服务器正常运行,问题出在手动制作的HTTP请求上,由于某些原因它格式不正确。
使用request模块可以解决:
var request = require('request');

request({
    method: 'POST',
    url: 'http://127.0.0.1:5000',
    // body: '{"foo": "bar"}'
    json: {"foo": "bar"}
}, (error, response, body) => {
    console.log(error);
    // console.log(response);
    console.log(body);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接