I am playing around with a really simple express.js 4.0.0 mongoose CRUD application / api. I am using postman to test it. I created some entries in the database by posting. Now when I try to delete one of them it seems to work but the first time I use GET after that, postman hangs. The same happens in the browser. It just keeps showing the loading spinner. The problem is not with mongoose because when I use a GET route, the remove() works.
UPDATE This seems to be an issue with chrome ( v. 36.0.1985.125 ) In Firefox and Sarafi it works. So, maybe this is a caching issue? I tried setting headers in postman like suggested here but it did not help.
Here is the code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser());
var router = express.Router();
/*
UPDATE
Suspecting it is a caching issues in chrome, now using this middleware to prevent caching
*/
router.use(function(req, res, next) {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
});
/* UPDATE */
app.use('/', router);
router.get('/', function(req, res){
res.send('Homepage');
});
var server = app.listen(3000, function(){
console.log('Listening to port %d', server.address().port);
});
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
var Bear = mongoose.model('Bear', BearSchema);
router.route('/bears')
.post(function(req, res){
var bear = new Bear();
bear.name = req.body.name;
bear.save(function(err){
if(err){
res.send(err);
return;
}
res.json({ message: 'Bear created' });
});
})
.get(function(req, res){
Bear.find(function(err, bears){
if(err){
res.send(err);
return;
}
res.json(bears);
});
});
router.route('/bears/:bear_id')
.delete(function(req, res){
Bear.remove({
_id: req.params.bear_id
}, function(err, num){
if(err){
res.send(err);
return;
}
if( num === 0 ){
res.json({ message: 'Nothing deleted' });
return;
}
res.json({ message: 'Successfully deleted' });
});
});