jquery 使用 AJAX 向Flask发送post请求(表单提交),405错误,可能是CORS问题?

p1iqtdky  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(118)

我试图发送一个POST请求从表单提交使用 AJAX ,jQuery在客户端。在服务器端使用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 )。我认为错误不在 flask 路由本身,因为由于405,POST请求不允许访问。我已经用GET测试过了,得到了一个status 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"

3qpi33ja

3qpi33ja1#

405错误代码表示不允许使用的方法。
你必须在路由上允许POST方法,像这样:

@app.route("/", methods = ["POST"])
def index():
  ...

字符串

相关问题