javascript - Flask 看不到 Node 发送的 JSON 数据

标签 javascript python json node.js flask

我正在尝试使用 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

最佳答案

Python Server 没有问题,运行正常,问题出在手工制作的 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);
});

关于javascript - Flask 看不到 Node 发送的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39395798/

相关文章:

javascript - AddRows 接收 PHP 数组

javascript - 使用 browserify/envify 删除 process.env.NODE_ENV?

python - 使用 python 在应用程序引擎中创建 POST 服务

javascript - 将 JSON "rows"与 "colums"合并到新对象中

java - JSON 字符串验证 [Spring Boot] - 约束零值

jQuery 1.4 破坏了我的程序

javascript - 这个奇怪的 JavaScript 素数检查函数是如何工作的?

javascript - 我怎样才能让这个脚本变得更好?

python - SQlite3 和 python 中的日期时间对象

Python 合并列表