提供多种内容类型

时间:2014-04-23 12:23:03

标签: node.js express url-routing

我正在使用Express创建网站和API,我想在相同的路径上提供多种内容类型(JSON,XML,HTML)。在Express中有更好的方法来编写以下内容:

// Serve JSON requests
app.get('/items/', function(req, res, next){
    if(!req.accepts('application/json')){
        return next();
    }

    res.end([1,2,3,4,5]);
});

// Serve XML requests
app.get('/items/', function(req, res, next){
    if(!req.accepts('application/xml')){
        return next();
    }

    res.end('<items><item>1</item><item>2</item><item>3</item><item>4</item><item>5</item></items>');
});

// Serve HTML requests
app.get('/items/', function(req, res, next){
    if(!req.accepts('text/html')){
        return next();
    }

    res.end('<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>');
});

特别是,上面的代码似乎相当重复,可能有更标准的方法来编写它。

1 个答案:

答案 0 :(得分:3)

有response.format方法,它使用基于&#34; Accept&#34;选择某种渲染方法。头。 http://expressjs.com/4x/api.html#res.format

响应可能如下所示:

res.format({
  text: function(){
    res.send('hey');
  },

  html: function(){
    res.send('hey');
  },

  json: function(){
    res.send({ message: 'hey' });
  }
});
相关问题