405 不允许方法 - JSON - 请求的 URL 不允许使用该方法

目前,引入了 JSON 来处理请求表单。我已经不止一次地编写了课程中解释的代码,并且我有 99% 的信心我确实正确地编写了所有内容。但当我尝试使用请求表单时,我总是收到错误“405 method not allowed”。网上搜索没有得到任何结果,我找不到解决我的问题的方法。下面是它应该运行的 python 路线:


 @app.route('/todos/create', methods=['POST'])

 def create_todo():

    description = request.get_json()['description']

    todo = Todo(description=description)

    db.session.add(todo)

    db.session.commit()

    return jsonify({

        'description': todo.description

    })

这里是 HTML 脚本


 <script>

            document.getElementById('form').onsubmit = function(e){

                e.preventDefault(); 

                fetch('/todos/create', {

                    method: 'POST',

                    body: JSON.stringify({

                        'description': document.getElementById('description').value

                    }),

                    headers: {

                        'Content-Type': 'application/json'

                    }

                }) 

                .then(function(response){

                    return response.json(); 

                })

                .then(function(jsonResponse){

                    console.log(jsonResponse);

                    const lil_item = document.createElement('LI'); 

                    lil_item.innerHTML = jsonResponse['description'];

                    document.getElementById('todos').appendChild(lil_item); 

                }); 

            }

        </script>

我希望有人能帮助我,我真的不知道如何解决这个问题。提前致谢。


慕少森
浏览 219回答 1
1回答

白板的微信

在您的 html 文档中,表单对象没有 id。在 javascript 代码中,您正在查找 id = "form" 的对象上的提交事件,但这样的元素不存在。所以你只需要改变:<form&nbsp;id="myForm"&nbsp;method="post"> &nbsp;&nbsp;&nbsp;&nbsp;<input&nbsp;type="text"&nbsp;id="description"&nbsp;name="description"&nbsp;/> &nbsp;&nbsp;&nbsp;&nbsp;<input&nbsp;type="submit"&nbsp;name="Create"&nbsp;/> </form>然后在JS中:document.getElementById('myForm').onsubmit&nbsp;=&nbsp;...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript