当我尝试在Express中执行PUT请求时,它会给我错误,我不确定它的含义。
这是我的玉:
extends layout
block content
form(method="post" action="/meals/#{meal[0].id}", id="mealForm")
input(type="hidden", name="_method", value="PUT")
h4 Meal Type
input.span3(id="mealType", type="text", name="MealType", value="#{meal[0].meal_type}")
br
h4 Meal Details
input.span3(id="mealDetails", type="text", name="MealDetails", value="#{meal[0].meal_details}")
br
input.btn(type="submit", class="btn btn-primary btn-lg" value="Update")
form(method="post" action="/meals/#{meal[0].meal_id}", id="mealForm")
input(type="hidden", name="_method", value="DELETE")
input.btn(type="submit", class="btn btn-danger btn-lg" style='margin-left: 1px;' value="Delete")
我不明白为什么这不起作用。这是我的app.js:
app.put('/meals/:id', meal.getMeal)
在meal.js
exports.getMeal = function(req, res){
console.log('sa')
id = req.params.id
query = "Select * \
From nutrition \
Where id=%"
query = query.replace(/%/g, id)
db.query(query, function(err, row) {
console.log(query);
if (err) console.log(err)
res.render('edit', { meal: row });
})
}
堆栈追踪:
500 TypeError: Object PUT,DELETE has no method 'toLowerCase'
at Object.methodOverride [as handle] (\middleware\methodOverride.js:37:30)
答案 0 :(得分:2)
您的问题是您将HTML表单嵌套在Jade模板中。 你基本上做的是:
<form method="post" action="/meals/#{meal[0].id}" id="mealForm">
<input type="hidden" name="_method" value="PUT">
<form method="post" action="/meals/#{meal[0].meal_id}" id="mealForm">
<input type="hidden" name="_method" value="DELETE">
</form>
</form>
表格不能嵌套。您可以在一个页面上拥有更多这些页面,但它们不能重叠或嵌套。例如:
<form method="post" action="/meals/#{meal[0].id}" id="mealForm">
<input type="hidden" name="_method" value="PUT">
</form>
<form method="post" action="/meals/#{meal[0].meal_id}" id="mealForm">
<input type="hidden" name="_method" value="DELETE">
</form>
您的代码的副作用是它然后发送到Express作为数组[“PUT”,“DELETE”](因为您的表单中有两个_method字段 - 第二个嵌套表单被忽略)而不是“ PUT“或”删除“。 Express尝试将接收的方法转换为小写进行比较,但是Array没有String的方法toLowerCase。
你可能只需修复你的Jade模板缩进:
extends layout
block content
form(method="post" action="/meals/#{meal[0].id}", id="mealForm")
input(type="hidden", name="_method", value="PUT")
h4 Meal Type
input.span3(id="mealType", type="text", name="MealType", value="#{meal[0].meal_type}")
br
h4 Meal Details
input.span3(id="mealDetails", type="text", name="MealDetails", value="#{meal[0].meal_details}")
br
input.btn(type="submit", class="btn btn-primary btn-lg" value="Update")
form(method="post" action="/meals/#{meal[0].meal_id}", id="mealForm")
input(type="hidden", name="_method", value="DELETE")
input.btn(type="submit", class="btn btn-danger btn-lg" style='margin-left: 1px;' value="Delete")