Express中 res.format()怎么用呀
发布于 9 年前 作者 wanggao421 6599 次浏览 最后一次编辑是 8 年前 来自 问答
app.get('/', function(req, res){
  res.format({
    html: function(){
      res.send('<ul>' + users.map(function(user){
        return '<li>' + user.name + '</li>';
      }).join('') + '</ul>');
    },

    text: function(){
      res.send(users.map(function(user){
        return ' - ' + user.name + '\n';
      }).join(''));
    },

    json: function(){
      res.json(users);
    }
  });
});

上面的代码, res.format(obj)返回页面的都是obj的第一个方法,也就是上面的 html方法。 我想问下text,json方面怎么用? 在什么情况下用?

4 回复

找到文档了,知道怎么用了… express API

res.format(object)

设置特定请求头的响应。 这个方法使用 req.accepted, 这是一个通过质量值作为优先级顺序的数组, 第一个回调会被执行。 当没有匹配时,服务器返回一个 406 “Not Acceptable”, 或者执行default 回调

Content-Type 在callback 被选中执行的时候会被设置好, 如果你想改变它,可以在callback内使用res.set()或者 res.type() 等

下面的例子展示了在请求头设置为"application/json" 或者 “/json"的时候 会返回{ “message”: “hey” } 如果设置的是"/*” 那么所有的返回都将是"hey"

res.format({ ‘text/plain’: function(){ res.send(‘hey’); },

‘text/html’: function(){ res.send(’

hey ’); },

‘application/json’: function(){ res.send({ message: ‘hey’ }); } });

根据不同的请求头内容类型,反回对应类型的数据(text/html/json) untitled1.png

LZ下一个postman(chrome插件)来方便测试。 楼上curl命令很Nice。

回到顶部