Flask看不到Nod发送的JSON数据

2024-04-19 22:24:03 发布

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

我试图使用Node将JSON数据发送到Flask,但无法读取Flask中的数据。我试着在烧瓶里打印request.data,但没有输出任何东西。我也尝试打印request.json,但它返回了400个响应。为什么Flask看不到节点发送的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()
^{pr2}$

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.exe 127.0.0.1:5000 --header "Content-Type: application/json" --data {\"foo\":\"bar\"}
POST

Tags: 数据namefromimportjsonappflaskdata
1条回答
网友
1楼 · 发布于 2024-04-19 22:24:03

Python服务器正常,运行正常,问题出在手工构建的http请求中,由于某种原因,它的格式不正确。在

使用^{}模块可以:

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);
});

相关问题 更多 >