SailsJS返回200状态代码而不是304

时间:2014-04-17 21:32:09

标签: rest sails.js

我目前正在试用Sails framework,到目前为止,我印象非常深刻。然而,我注意到的一个奇怪的事情是服务器为所有记录返回200 OK而不是304 Not Modified状态代码(即使没有更改)。

有没有办法让Sails为未修改的记录返回304?我问的原因是,这似乎是best practice ,并被GoogleFacebook等大型玩家使用。

1 个答案:

答案 0 :(得分:1)

简短的回答是肯定的,您只需在回复中设置Last-Modified标题即可。 "Sails is built on Express",使用fresh(npmjs.org/package/fresh)到compare the request and response headers

简单示例(基于Sails 0.10.0-rc5):

  1. sails new test304response
  2. cd test304response
  3. sails generate api user - >生成User.jsUserController.js
  4. 修改api/models/User.js

    module.exports = {
        schema: true,
        attributes: {
            name: {
                type: 'string',
                required: true
            }
        }
    };
    
  5. 修改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. 转到localhost:1337/user/create?name=Joe - >创建新用户
  8. 转到localhost:1337/user/1 - >查询id为
  9. 的用户
  10. 刷新localhost:1337/user/1 - >查询同一用户,Last-Modified未更改
  11. 响应的状态为304 – Not Modified(即使在Chrome DevTools中,只要您未在设置中明确禁用它,它实际上会执行缓存。)
  12. 免责声明:我刚刚开始学习风帆和节点,所以我可能错过了一个更简单/更清洁的解决方案。我也不完全确定,在所有情况下设置Last-Modified都足够了。但是,我觉得你更有兴趣知道是否有可能而不是最佳实践。

    希望这会有所帮助。 :)

相关问题