node.js - PUT and DELETE always route to GET in Node + Express -
i'm beginner in node/express. tried create crud application stuck @ update , delete. think router code problematic don't know why. next code in controller, works put
, delete
. route get
. tried utilize next();
returns error: can't set headers after sent.
.
i can create delete works using get /:company_id/delete
it's not , standardized solution. how can update , delete process worked?
'use strict'; var companies = require('../../models/companies'); module.exports = function (router) { // index // accessed @ http://localhost:8000/companies router.get('/', function (req, res) { companies.find(function(err, model) { if (err) { res.send(err); } else { res.format({ json: function () { res.json(model); }, html: function () { res.render('companies/index', model); } }); } }); }); // create view // accessed @ http://localhost:8000/companies/create router.get('/create', function (req, res) { res.render('companies/create'); }); // create info // accessed @ post http://localhost:8000/companies router.post('/', function (req, res) { var name = req.body.name && req.body.name.trim(); var type = req.body.type && req.body.type.trim(); // validation if (name === '') { res.redirect('/companies/create'); return; } var model = new companies({name: name, type: type}); model.save(function(err) { if (err) { res.send(err); } else { res.redirect('/companies'); } }); }); // read // accessed @ http://localhost:8000/companies/:company_id router.get('/:company_id', function(req, res) { companies.findbyid(req.params.company_id, function(err, model) { if (err) { res.send(err); } else { res.render('companies/read', model); } }); }); // update view // accessed @ http://localhost:8000/companies/:company_id/edit router.get('/:company_id/edit', function(req, res) { companies.findbyid(req.params.company_id, function(err, model) { if (err) { res.send(err); } else { res.render('companies/edit', model); } }); }); // update info // accessed @ set http://localhost:8000/companies/:company_id router.put('/:company_id', function(req, res) { companies.findbyid(req.params.company_id, function(err, model) { if (err) { res.send(err); } else { model.name = req.body.name; model.type = req.body.type; model.save(function(err) { if (err) { res.send(err); } else { res.redirect('/companies'); } }); } }); }); // delete // accessed @ delete http://localhost:8000/companies/:company_id router.delete('/:company_id', function (req, res) { companies.remove({ _id: req.params.company_id }, function(err) { if (err) { res.send(err); } else { res.redirect('/companies'); } }); }); };
html forms back upwards get
, post
. xmlhttprequest supports put
, delete
however, may have go route or utilize method-override allow html forms submit using other http verbs.
node.js express
No comments:
Post a Comment