使用Fetch API将JSON对象发送到Flask服务器会导致400 Bad Request。

huangapple go评论69阅读模式
英文:

Sending A Json object through Fetch API to a Flask Server leads to a 400 Bad Request

问题

我尝试发送一些JSON数据到服务器,按照一些在线文章和官方的Flask文档,但我一直收到400错误。到目前为止,我尝试过的方法都没有成功。

我了解到,如果Flask没有正确格式化的JSON数据,它会引发此错误,还有一个要求的请求必须指定Content-Type标头为application/json,否则会发生相同的情况。

我复制了一些官方文档中的代码,以下是我到目前为止的代码:

在我的Flask应用程序中的视图函数:

@main.route('/test', methods=['GET','POST'])
def test():

    if request.method == 'POST':
        print(request.method)
        print(request.headers.get('Content-Type'))
        print(request.is_json)
# 运行时会导致400错误
        #print(request.json)

    return render_template('test.html')

在test.html中的以下脚本标签:

<script>
    let data = {"data": "Hello World!"}

    document.querySelector('#main').addEventListener('click', function () {
        fetch('/test', {
            method: "POST",
            body: JSON.stringify(data),
            headers: {"Content-Type": "application/json"},
            credentials: "same-origin"
        })
        .then(response => console.log(response.json))
    })
</script>

每当我点击按钮来POST数据时,我在终端中看到以下内容:

POST
text/plain;charset=UTF-8
False

因此,我认为导致所有这些问题的原因是HTTP请求的Content-Type标头没有正确设置。

如果您有任何关于如何修复这个问题的想法,将不胜感激。

英文:

I was trying to send some JSON data to the sever following some online articles and the official flask documentation, but I keep getting a 400 error. What I've tried hasn't worked so far.

I have read that if flask doesn't get properly formated JSON data it pushes this error and also that the read of the request must specify Content-Type header as application/json or else the same happens.

I copied some of my code off the official Documentation and this is what i have so far:

a view function inside my flask application:

@main.route(&#39;/test&#39;, methods=[&#39;GET&#39;,&#39;POST&#39;])
def test():

    if request.method == &#39;POST&#39;:
        print(request.method)
        print(request.headers.get(&#39;Content-Type&#39;))
        print(request.is_json)
#this gets me the 400 when run
        #print(request.json)

    return render_template(&#39;test.html&#39;)

the following scrip tag inside test.html:

&lt;script&gt;
    let data = {&quot;data&quot;: &quot;Hello World!&quot;}

    document.querySelector(&#39;#main&#39;).addEventListener(&#39;click&#39;, function () {
        fetch(&#39;/test&#39;, {
            method: &quot;POST&quot;,
            body: JSON.stringify(data),
            headers: {&quot;Content-Type&quot;: &quot;application/json&quot;},
            credentials: &quot;same-origin&quot;
        })
        .then(response =&gt; console.log(response.json))
    })
&lt;/script&gt;

Every time I hit the button to POST the data I get the following showing in my terminal

POST
text/plain;charset=UTF-8
False

So I assume what is causing all of this is that the Content-Type header of the HTTP request is not setting properly.

Any ideas on how I could fix this would be apreciated

答案1

得分: 1

需要指定您要定位的完整端点。

from flask import Flask, request

# 创建Flask应用
app = Flask(__name__)

# POST端点
@app.route('/post', methods=['POST'])
def endpoint():
    data = request.get_json()
    
    return data

# 运行应用
if __name__ == '__main__':
    app.run(debug=True)
const endpoint = "http://127.0.0.1:5000/post";

// 发送POST请求到端点
const response = fetch(endpoint, {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "John Doe",
    })
});

response.then(data => {
    data.text().then(text => {
        console.log(text);
    })
})
英文:

You need to specify the full endpoint of what you are targeting.

from flask import Flask, request

# create the flask app
app = Flask(__name__)

# post endpoint
@app.route(&#39;/post&#39;, methods=[&#39;POST&#39;])
def endpoint():
    data = request.get_json()
    
    return data

# run the app
if __name__ == &#39;__main__&#39;:
    app.run(debug=True)
const endpoint = &quot;http://127.0.0.1:5000/post&quot;;

// post request to endpoint
const response = fetch(endpoint, {
    method: &quot;POST&quot;,
    headers: {
        &quot;Content-Type&quot;: &quot;application/json&quot;
    },
    body: JSON.stringify({
        name: &quot;John Doe&quot;,
    })
});

response.then(data =&gt; {
    data.text().then(text =&gt; {
        console.log(text);
    })
})

答案2

得分: 0

根据您的代码和收到的错误消息,问题可能与请求头部设置不正确有关。

您在JavaScript代码中设置了Content-Type标头为"application/json",这是正确的。但是,您的Flask视图函数未正确检查Content-Type标头。您可以像这样检查:

if request.is_json:
    data = request.get_json()
    print(data)
else:
    print("请求不是JSON")

这会使用请求对象的is_json属性来检查请求是否为JSON格式。如果是,那么您可以使用get_json()方法提取数据。如果不是,您可以打印一条消息或返回一个错误。

此外,您可能还想添加一个try-except块来捕获解析JSON数据时可能发生的任何错误:

if request.is_json:
    try:
        data = request.get_json()
        print(data)
    except Exception as e:
        print("解析JSON数据时出错:", e)
        return "请求无效", 400
else:
    print("请求不是JSON")
    return "请求无效", 400

这将捕获解析JSON数据时的任何异常,并返回带有400状态代码的"请求无效"错误。

希望这有所帮助!

英文:

Based on your code and the error message you are receiving, the issue might be related to the request header not being set correctly.

You are setting the Content-Type header in your JavaScript code to "application/json", which is correct. However, your Flask view function does not check the Content-Type header correctly. You can check it like this:

if request.is_json:
    data = request.get_json()
    print(data)
else:
    print(&quot;Request is not JSON&quot;)

This checks whether the request is in JSON format using the is_json property of the request object. If it is, then you can use the get_json() method to extract the data. If it's not, you can print a message or return an error.

Additionally, you might want to add a try-except block to catch any errors that might occur when parsing the JSON data:

if request.is_json:
    try:
        data = request.get_json()
        print(data)
    except Exception as e:
        print(&quot;Error parsing JSON data:&quot;, e)
        return &quot;Bad Request&quot;, 400
else:
    print(&quot;Request is not JSON&quot;)
    return &quot;Bad Request&quot;, 400

This will catch any exceptions when parsing the JSON data and return a "Bad Request" error with a 400 status code.

I hope this helps!

huangapple
  • 本文由 发表于 2023年2月18日 04:30:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75489009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定