Reputation: 1095
I'm currently trying out the Sails framework and so far I'm quite impressed. One of the odd things I noticed however is that the server returns a 200 OK
rather than a 304 Not Modified
status code for all records (even when unchanged).
Is there a way to make Sails return a 304 for unmodified records? The reason I'm asking is that this seems to be the best practice and used by some big players like Google and Facebook.
Upvotes: 1
Views: 913
Reputation: 248
The short answer is yes, you simply have to set the Last-Modified
header on your responses.
"Sails is built on Express", which uses fresh (npmjs.org/package/fresh) to compare the request and response headers.
Simple example (based on Sails 0.10.0-rc5
):
sails new test304response
cd test304response
sails generate api user
-> generates User.js
and UserController.js
edit api/models/User.js
module.exports = {
schema: true,
attributes: {
name: {
type: 'string',
required: true
}
}
};
edit api/controllers/UserController.js
module.exports = {
find: function (req, res, next) {
console.log('find:', req.fresh);
User.findOne(req.param('id'), function foundUser(err, user) {
// set the Last-Modified header to the updatedAt time stamp
// from the model
res.set('Last-Modified', user.updatedAt);
res.json(user);
});
},
};
sails lift
localhost:1337/user/create?name=Joe
-> creates a new Userlocalhost:1337/user/1
-> queries the User with id 1localhost:1337/user/1
-> queries the same User, Last-Modified wasn't changed 304 – Not Modified
status (even in the Chrome DevTools, which actually do caching as long as you don't explicitly disable it in the settings).Disclaimer: I just started to learn sails and also node, so I might have missed a simpler/cleaner solution. I'm also not completely certain, that setting Last-Modified
is enough in all cases. However, I had the feeling that you are more interested to know if it is possible and not to get a best practice implementation.
Hope this helps. :)
Upvotes: 1