使用方法覆盖包、express 和 express-handlebars 在 node.js 中试验 REST http 方法。奇怪的是,我可以使用把手循环遍历一组对象,但是当我尝试将特定 id 分配给 url 方法时,它只会分配该循环中的第一项。
在 html 页面上将显示 foo 1 bar 2 foobar 3
当单击按钮时,无论选择哪个按钮,单击按钮后都会显示为:您的 ID 为:1
有人可以指出为什么我的按钮方法 url 没有被分配特定的 id,即使我的页面可以读取它们?
服务器.js
const express = require('express');
const exphbs = require('express-handlebars');
const methodOverride = require('method-override');
const app = express();
app.use(methodOverride('_method'));
var PORT = process.env.PORT || 3000;
const products = [
{id: 5, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'foobar'}
];
app.engine('handlebars', exphbs({
defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');
app.get('/', (req, res, next) => {
res.render("index", { products });
});
app.delete('/:id?', (req, res, next) => {
res.send('your id is: ' + req.params.id);
});
app.listen(PORT, ()=> console.log('This s*** is bananas'));
index.handlebars
<ul>
{{#each products}}
<li>{{this.name}}</li>
<form method="POST" action="/{{this.id}}?_method=DELETE">
<button type="submit">DELETE</button>
<form>
{{/each}}
</ul>