服务多种内容类型 [英] Serving multiple content types
本文介绍了服务多种内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Express创建网站和API,我想在同一路径上提供多种内容类型(JSON,XML,HTML).在Express中,有一种更好的方法可以编写以下内容:
I'm creating a website and API with Express, I want to serve multiple content types (JSON, XML, HTML) on the same paths. In Express is there a better way to write the following:
// 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>');
});
尤其是上面的代码似乎很重复,可能有一种更标准的编写方式.
In particular, the above code seems rather repetitive, there's probably a more standard way to write this.
推荐答案
有response.format方法,该方法使用基于"Accept"标头选择某些呈现方法. http://expressjs.com/4x/api.html#res.format
There is response.format method which uses selects certain render method based on the "Accept" header. 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' });
}
});
这篇关于服务多种内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文