Well, I'm reading the MEAN Machine book and following it's examples. I'm trying to figure out what's wrong with my code so it won't make any DELETE request. GET, PUT and POST works as should.
I have this code on my server.js:
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization');
next();
});
var apiRouter = express.Router();
apiRouter.route('/users/:user_id')
.get( function (req, res) {
User.findById( req.params.user_id, function (err, user) {
if (err) res.send (err);
res.json(user);
});
})
.put( function (req, res) {
User.findById(req.params.user_id, function (err, user) {
if (err) res.send(err);
if (req.body.name) user.name = req.body.name;
if (req.body.username) user.username = req.body.username;
if (req.body.password) user.password = req.body.password;
user.save( function (err){
if (err) send (err);
res.json({message: 'User updated'});
});
})
.delete( function (req, res) {
User.remove({
_id: req.params.user_id
}, function (err, user) {
if (err) return res.send(err);
res.json({ message: 'Deleted' });
});
});
});
I have a set of users the Modulus MongoDB database and, when I try to use POSTMAN with localhost:8080/api/users/5610e5576d827dc41fb8e6e, POSTMAN says
Cannot DELETE /api/users/5610e5576d827dc41fb8e6e
while my Node server with Morgan says
DELETE /api/users/5610e5576d827dc41fb8e6e 404
Why I'm getting a 404? What Am I doing wrong?
Full code
You've placed closing brackets of put()
in wrong place. So you're defining your delete
router inside the put()
router:
This is your code after proper indentation:
.put( function (req, res) {
User.findById(req.params.user_id, function (err, user) {
if (err) res.send(err);
if (req.body.name) user.name = req.body.name;
if (req.body.username) user.username = req.body.username;
if (req.body.password) user.password = req.body.password;
user.save( function (err){
if (err) send (err);
res.json({message: 'User updated'});
});
})
.delete( function (req, res) { // <===== defined inside 'put',
User.remove({
_id: req.params.user_id
}, function (err, user) {
if (err) return res.send(err);
res.json({ message: 'Deleted' });
});
});
})
So, just move the delete
router outside of put
router callback
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With