NotJustClarkKent
NotJustClarkKent

Reputation: 1095

SailsJS returns a 200 Status Code Rather Than 304

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

Answers (1)

Jan
Jan

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):

  1. sails new test304response
  2. cd test304response
  3. sails generate api user -> generates User.js and UserController.js
  4. edit api/models/User.js

    module.exports = {
        schema: true,
        attributes: {
            name: {
                type: 'string',
                required: true
            }
        }
    };
    
  5. 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);
            });
        },
    };
    
  6. sails lift

  7. go to localhost:1337/user/create?name=Joe -> creates a new User
  8. go to localhost:1337/user/1 -> queries the User with id 1
  9. refresh localhost:1337/user/1 -> queries the same User, Last-Modified wasn't changed
  10. The response has a 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

Related Questions