【问题标题】:Method is not allowed for requested URL请求的 URL 不允许使用方法
【发布时间】:2020-05-01 15:48:22
【问题描述】:

我不知道是什么导致了这个出错。也许我认为这是一件需要改变的小事,但我找不到这个。请帮助我解决这个问题。 我想将文件地址发送到服务器并对其进行格式化,该代码我没有添加但地址没有被格式化。帮助将不胜感激

    <div class="container">
         <form class="form-signin" method="post" role="form">
             <h2 class="form-signin-heading">Please Sign Up </h2>
             <div>
             <input type="text" name="address" placeholder="Drivers" class="form-control col-3 mr-4">
        </div>
        <div>
            <button class="btn btn-outline-light d-inline-block" style="width: 150px;float: left;" id="upload">Upload</button>
        </div>
        </form>
     </div>
$(function() {
     console.log("working")
    $('#upload').click(function() {
        console.log("inside is working")
        $.ajax({
            url: '/signUpUser',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response)
                console.log(data.address);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/signUpUser', methods=['GET','POST'])
def signUpUser():
    if request.method=='POST':
        address=request.form['address']
    return jsonify({'address':address}); 

【问题讨论】:

  • 可以添加完整的回溯吗?
  • 您的按钮是type=submit,并且您没有取消默认操作,因此您的form 正在发布到'/' 而不是$.ajax(这可能工作正常) - 更改按钮到&lt;button type='button'&gt;
  • 嘿,freedomn,感谢您的帮助。问题已经解决。我不知道为什么我会收到错误,因为我已经为其他功能尝试了相同的方式。它工作正常感谢您的帮助

标签: javascript python jquery ajax flask


【解决方案1】:

Method not allowed 表示尚未为GET 或很可能POST 设置路由,此错误来自您的API,这意味着您尚未在路由上指定应该使用什么方法,因此它失败了。我很确定它默认为GET,但如果你打电话给POST,那么它会向你抱怨这个错误。没有看到您的 api 代码,我们可以提供尽可能多的帮助。

【讨论】:

    【解决方案2】:

    问题是因为您没有阻止标准表单提交。这意味着您正在向当前页面发送标准表单请求,该页面未配置为接收 POST 请求,因此您会看到错误。

    要解决此问题,请将submit 事件处理程序附加到form,并在作为处理函数参数提供的事件上调用preventDefault()

    $(function() {
      $('form.form-signin').on('submit', function(e) {
        e.preventDefault();
    
        $.ajax({
          url: '/signUpUser',
          data: $(this).serialize(),
          type: 'POST',
          success: function(response) {
            console.log(response)
            // console.log(data.address); < commented out as 'data' is not defined anywhere
          },
          error: function(x, s, e) {
            console.log(x, s, e);
          }
        });
      });
    });
    

    【讨论】:

    • 谢谢我用另一种方式做了,但你的方式更清晰
    猜你喜欢
    • 2016-12-12
    • 2021-08-16
    • 2017-01-10
    • 2014-01-08
    • 2020-07-30
    • 2021-11-13
    • 2020-08-27
    • 2016-04-23
    • 2023-03-09
    相关资源
    最近更新 更多