要使用Put之前,在index.js中require method-overrise
const methodOverride = require('method-override')
app.use(methodOverride('_method'))
<form action="/products/<%=product._id%>?_method=PUT" method="POST">
index.js
const methodOverride = require('method-override')
app.use(methodOverride('_method'))
app.get('/products/:id/edit', async (req, res) => {
const { id } = req.params;
const product = await Product.findById(id);
res.render('products/edit', { product })
})
app.put('/products/:id', async (req, res) => {
const { id } = req.params;
const product = await Product.findByIdAndUpdate(id, req.body, { runValidators: true, new: true });
res.redirect(`/products/${product._id}`);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit product</title>
</head>
<body>
<h1>Edit a product </h1>
<form action="/products/<%=product._id%>?_method=PUT" method="POST">
<label for="name">Name</label>
<input type="text" name="name" id="name" placeholder="product name" value="<%=product.name%>">
<label for="price">price</label>
<input type="number" name="price" id="price" placeholder="price" value="<%=product.price%>">
<label for="category">Select category</label>
<select name="category" id="category">
<option value="fruit">fruit</option>
<option value="vegetable">vegetable</option>
<option value="dairy">dairy</option>
</select>
<button>Submit</button>
<!-- Submit按钮一旦点击,提交页面/products, post,跟index.js里面的app.post('/products',。。。)连接着 -->
</form>
<a href="/products/<%=product._id%>">Cancel</a>. //cancel回到待编辑页面
</body>
</html>