project structure
.app.js .routes/ ....resources.js
i have following server instance running:
app.js
"use strict"; const app = require('express')(); const resources = require('./routes/resources'); app.use('/', resources); const server = app.listen('3000', () => { let host = server.address().address; host = (host == '::' ? 'localhost' : host); const port = server.address().port; // log console.log('listening @ http://%s:%s', host, port); });
i have , post requests working (routes/resources.js) fine i.e.
"use strict" const express = require('express'); const router = express.router(); const bodyparser = require('body-parser'); //parser router.use(bodyparser.json()); // parsing application/json router.use(bodyparser.urlencoded({ extended: true })); // parsing application/x-www-form-urlencoded // data let resources = [{ id: 1, name: 'foo' }]; // post router.post('/resources', (req, res) => { let item = req.body; //send status if (!item.id) { return res.sendstatus(500); } // saved string, id must int item.id = parseint(item.id, 10); // add id resources.push(item); // send response of new resource res.send('/resources/' + parseint(item.id, 10)); });
using postman can post, following put , delete give me cannot delete /resources/ message:
// put router.put('/resources/:id', (req, res) => { // id request let id = parseint(req.body.id, 10); // find existing id in resources let existingitem = resources.filter(r => r.id === id)[0]; // if doesn't exist if(!existingitem) { let item = req.body; item.id = id; resources.push(item); res.setheader('location', '/resources/' + id); res.sendstatus(201) } else { existingitem.name = req.body.name; res.sendstatus(204); } }); // delete router.delete('/resources/:id', (req, res) => { let id = parseint(req.body.id, 10); let existingitem = resources.filter(r => r.id === id)[0]; if (!existingitem) { return res.sendstatus(404) } resources = resources.filter(r => r.id !== id); res.sendstatus(204) });
head scratching why, though may answer staring me in face. appreciated!
doh, gave delete , put paths /:id parameter
router.delete('/resources/:id...) router.put('/resources/:id'...)
when merely pointing delete / put requests '/resources/ inside postman.
thanks @molda - made me realise mistake!
Comments
Post a Comment