【问题标题】:How to make route redirect or send JSON back depending on accept headers?如何根据接受标头进行路由重定向或发回 JSON?
【发布时间】:2013-07-24 04:29:07
【问题描述】:

如果用户访问路由并且接受标头仅允许 JSON,我想发回 JSON,如果用户访问路由并且接受标头不允许 JSON,我想将用户重定向到页面。

我的解决方案非常 hacky,但它涉及检查 req.headers.accept 并查看字符串是否包含 json。如果是,我返回 JSON,否则,我重定向。有没有更优化的解决方案?

【问题讨论】:

  • 你能分享一些示例代码吗?

标签: javascript node.js express


【解决方案1】:

你可以试试res.format方法。

res.format({
  'application/json': function(){
    res.send({ message: 'hey' });
  },

  default: function(){
    res.redirect('nojson.html');
  }
});

【讨论】:

    【解决方案2】:

    cr0 所描述的方法可能是“正确的方法”。我不知道这种较新的辅助方法。

    该解决方案是正确的。您可以使用req.get 以不区分大小写的方式获取标头,并使用正则表达式检查值。通常我使用以下内容。

    module.exports = function() {
        function(req, res, next) {
          if(req.get("accept").match(/application\/json/) === null) {
            return res.redirect(406, "/other/location");
          };
          next();
        }
    }
    

    那么这可以作为中间件使用。

    app.use(require("./jsonCheck")());
    

    您还可以通过更改导出的函数来更详细地使用模块并重定向到自定义位置。

    module.exports = function(location) {
        function(req, res, next) {
          if(req.get("accept").match(/application\/json/) === null) {
            return res.redirect(406, location);
          };
          next();
        }
    }
    

    并像这样使用它

    app.use(require("./jsonRedirect")("/some.html"));
    

    【讨论】:

      猜你喜欢
      • 2014-12-01
      • 2021-09-30
      • 1970-01-01
      • 2014-12-24
      • 2015-12-10
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 2020-03-06
      相关资源
      最近更新 更多