0

使用方法覆盖包、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>
4

1 回答 1

0

您的问题是您的 HTML 无效。您在结束表单标记中缺少“/” </form>,. 您的浏览器在尝试理解无效标记时,只呈现第一个表单,带有action=/1. 所有按钮都提交此表单。

于 2018-05-13T04:09:38.470 回答