提问人:Sean.realitytester 提问时间:7/13/2023 最后编辑:Sean.realitytester 更新时间:7/13/2023 访问量:79
使用 AJAX、405 错误、可能的 CORS 问题向 Flask(表单提交)发送发布请求?
Sending a post request to Flask (form submit) with AJAX, 405 error, possible CORS issue?
问:
我正在尝试在客户端使用 Ajax、jQuery 从表单提交发送 POST 请求。在服务器端使用 Flask 处理提交的数据。
首先,我将显示 post 请求,该请求遇到 405-method not allowed 错误消息。
$("#lucky-form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
console.log("running this form")
var form = $(this);
var actionUrl = form.attr('http://127.0.0.1:5000/numberapi');
$.ajax({
type: "POST",
url: actionUrl,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
我已经安装了flask_cors并启用了CORS(app)以启用跨域请求(AJAX)。我认为错误不在于烧瓶路由本身,因为由于 405,不允许访问 POST 请求。我已经用 GET 对其进行了测试并获得状态 200 OK html 响应。
我相信这是在 JS/jQueryside 上发送请求的问题,但不确定它可能是什么。非常感谢您的帮助。
有关更多详细信息和上下文,这里是我的 Flask 路由,它应该接收和处理 POST 请求。
@app.route("/numberapi", methods=['GET','POST'])
@cross_origin()
def get_lucky_number():
"""recieves our AJAX request from the front end,"""
## here we will store the data of the users who use our lucky number app.
#this is just for reference, and we can use the data at a later point.
#when all of the inputted data is correct, we return the client with a lucky number and the fact
#we can collect data like what type of facts people want to know the most.
form = LuckyNumberForm()
converted = json.loads(bytes.decode(request.data))
birth_year = converted.get('birth_year')
color = converted.get('color').lower()
if form.validate_on_submit():
print("validated!")
if color not in valid_colors:
print("error of color")
form.color.errors = "Please pick a valid colour"
retrieved = jsonify(errors=form.color.errors)
#currently returning undefined.
elif valid_dob(birth_year) != True:
print("error of dob")
form.color.errors = "Please pick a valid birthyear between 1900 and 2000"
retrieved = jsonify(errors=form.birth_year.errors)
#currently returning undefined
else:
year_fact = get_dob_fact(birth_year)
number_fact = get_number_fact()
print(year_fact) #this is json
print(number_fact) #this is json
return [year_fact,number_fact]
return "csrf validation did not pass"
答:
0赞
ross714
7/13/2023
#1
405 错误代码表示不允许使用方法。
您必须在路由上允许方法,如下所示:POST
@app.route("/", methods = ["POST"])
def index():
...
评论
1赞
Sean.realitytester
7/13/2023
欣赏,实际上这是一个错别字,我在被剪断的烧瓶路由代码中遗漏了应用程序路由。我很抱歉,现在已经修改了,缺少“@app.route(”/numberapi“, methods=['GET','POST']) @cross_origin()”
评论