【问题标题】:Method Not Allowed The method is not allowed for the requested URL POST RequestMethod Not Allowed 请求的 URL POST 请求不允许使用该方法
【发布时间】:2020-08-27 00:19:16
【问题描述】:

我正在尝试让我的 POST 请求通过烧瓶工作。 它从 .py 文档中获取数据(工作正常。它以我想要的方式显示在表格中) 但不会让我发布到它。我总是得到错误:

不允许的方法 请求的 URL 不允许该方法。

控制台:“POST / HTTP/1.1”405 -

我的 JavaScript 代码:

  function addUserList() {
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", '/api/users', true);
    xhttp.onload = function() {
      if (xhttp.readyState == 4 && xhttp.status == 201) {
        alert("user created")
      }
      else{alert("Error")
    }
  };

    data = {fname: "Henry", lname: "Ford"}
    stringdata = stringify(data)

    console.log("function add user triggered")

    xhttp.send(stringdata);

}

还有我的主 app.py:

def getUserList():
   if request.method =='GET': 
       return jsonify({"data": userlist})
   if request.method =='POST': 
       repobj = json.loads(request.data)
       user = repobj['fname']
       user1 = repobj['lname']

       newid = userlist[-1]["id"]
       newuser = {"id":newid +1,
                  "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
                  "first_name":user,
                  "last_name":user1,
                  "email":"george.bluth@reqres.in",
                  "job": "Doctor"}
       userlist.append(newuser)
       resp = make_response("", 201)
       return resp

现在我正在尝试对 fname 和 lname 进行硬编码以查看其是否正常工作。

我是 Flask 的新手!

感谢您的支持!

【问题讨论】:

    标签: javascript html flask


    【解决方案1】:

    在定义函数getUserList 的app.py 中,必须在括号中添加:methods="GET", "POST"。 Flask 会自动处理GET 方法,但如果你明确表示该函数可以处理,则只能使用方法POST。最终会变成:def getUserList(methods="GET", "POST"):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 2016-01-22
      • 2021-03-15
      • 2016-04-23
      • 2022-11-02
      • 2012-06-22
      相关资源
      最近更新 更多