Experimenting with REST http methods in node.js using method-override package, express and express-handlebars. Oddly, I am able to loop through an array of objects using handlebars, but when I try to assign the specific id to the url method it will only assign the 1st item in that loop.
on html page will show foo 1 bar 2 foobar 3
when button click regardless of the button picked it will read after the button is clicked as: Your ID is: 1
Can someone point out why my button method urls are not getting assigned the specific id even though my page can read them?
server.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>
Your problem is that your HTML is invalid. Your are missing the "/" in your closing form tag, </form>
. Your browser, in trying to make sense of the invalid markup, is rendering only the first form, with action=/1
. All of the buttons submit this form.