Javascript数据发送到python-flask,带有ajax nad消息400-错误请求



Javascript数据用ajax和消息400发送到python烧瓶-错误的请求

我使用ajax,并将数据从js发送到flask。我发送一个名字";约翰;到url"/name";我想要烧瓶请求。实际上我可以请求并打印";约翰";。但有返回400-错误的请求。希望得到帮助!!!

这是我的代码:

HTML+JS:

<html>
<head>
<title>HOME ||</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
function send(){
var data={"name":"John"};
alert(data["name"]);
$.ajax({
type: 'POST',
url:"/name",
data:JSON.stringify(data),
contentType: 'application/json; charset=UTF-8',
});
document.location.href="/name";
};
</script>
</head>
<body>
<script>
send()
</script>
</body>
</html>

Python烧瓶:

from flask import Flask, render_template
from flask import request
import json
app = Flask(__name__, template_folder="html")
@app.route('/')
def home():
return render_template("index.html")
@app.route('/name', methods = ["GET", "POST"])
def name():
print(request.get_json(force=True)["name"])
return "ok"
app.run()

终端:

PS C:Pythonflasktest2> python app.py
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [06/May/2021 15:31:13] "GET / HTTP/1.1" 200 -
John
127.0.0.1 - - [06/May/2021 15:31:15] "POST /name HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2021 15:31:15] "GET /name HTTP/1.1" 400 -

您的问题在这里>> **document.location.href="/name";**这行代码正在向Flask中的/name调用get请求。

Inside/name您正在尝试获取**request.get_json(force=True)["name"]**,但这不在get请求中。

一种选择是删除document.location.href="name">所以您没有发送获取请求

或者你可以通过写以下内容来检查这个论点是否在Flask中通过:

如果request.get_json中的"name"(force=True(:print(request.get_json(force=True(["name"](返回";ok";其他:返回";ok">

这应该有望处理坏请求错误,因为我们在访问密钥之前正在检查密钥是否存在

最新更新