英文:
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('/test', methods=['GET','POST'])
def test():
if request.method == 'POST':
print(request.method)
print(request.headers.get('Content-Type'))
print(request.is_json)
#this gets me the 400 when run
#print(request.json)
return render_template('test.html')
the following scrip tag inside 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>
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('/post', methods=['POST'])
def endpoint():
data = request.get_json()
return data
# run the app
if __name__ == '__main__':
app.run(debug=True)
const endpoint = "http://127.0.0.1:5000/post";
// post request to endpoint
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);
})
})
答案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("Request is not JSON")
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("Error parsing JSON data:", e)
return "Bad Request", 400
else:
print("Request is not JSON")
return "Bad Request", 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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论