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



我正在Udacity上学习用Python开发web应用程序的课程。目前,它被引入了JSON来处理请求表单。我已经写了不止一次课上解释的代码,99%的人认为我写的所有东西都是正确的。但我总是犯错误";405方法不允许";当我尝试使用申请表时。在线搜索一无所获,我找不到解决问题的方法。下面是它应该运行的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>

我希望有人能帮我,我真的不知道该怎么解决。提前谢谢。

编辑-插入完整的HTML代码:

<html>
<head>
<title>
Todo App
</title>
</head>
<body>
<form method="post" >
<input type="text" id="description" name="description" />
<input type="submit" name="Create" />
</form>
<ul id="todos">
{% for d in data %}
<li>  {{d.description}}  </li>
{% endfor %}
</ul>
<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>
</body>
</html>

在html文档中,表单对象没有id。在javascript代码中,您正在查找id为"的对象上的提交事件;形式";,但这种元素并不存在。

所以你只需要改变:

<form id="myForm" method="post">
<input type="text" id="description" name="description" />
<input type="submit" name="Create" />
</form>

然后在JS:中

document.getElementById('myForm').onsubmit = ...

最新更新