我在hapijs中找不到任何渲染xml输出的文档,目前我的视图是这样渲染的:
server.route({
path: "/feed/{tag}",
method: "GET",
handler: function(req, resp) {
var tag = req.params.tag;
Post.findByTag(tag).sort({date: -1}).exec()
.then(function(posts){
resp.view("feed", {posts: posts, updated: posts[0].date}, {layout: false});
});
}
});
和我的车把模板feed.hbs
是:
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>{{ site.siteTitle }}</title>
<link href="{{site.siteBaseUrl}}"/>
<author>
<name>Adam Stokes</name>
</author>
<updated>{{updated}}</updated>
<id>{{site.siteBaseUrl}}</id>
{{#each posts}}
<entry>
<title>{{this.title}}</title>
<link href="{{site.siteBaseUrl}}/{{this.permalink}}"/>
<id>{{site.siteBaseUrl}}/{{this.permalink}}</id>
<updated>{{this.date}}</updated>
<summary>{{md this.md}}</summary>
</entry>
{{/each}}
</feed>
问题:
在浏览器中查看输出不会呈现为正常的xml输出,而是呈现为文本。
问题是我如何确保输出具有正确的报头以正确的xml格式呈现?
车把正确地呈现了XML,只是您的浏览器将其解释为HTML而不是XML。您只需要指明内容类型为XML:
server.route({
path: '/feed/{tag}',
method: "GET",
handler: function (request, reply) {
var tag = req.params.tag;
Post.findByTag(tag).sort({date: -1}).exec()
.then(function(posts){
var response = reply.view('feed', {posts: posts, updated: posts[0].date}, {layout: false});
response.type('application/xml');
});
}
});
除了:
我建议您使用标准参数名称request
和reply
。您选择的resp
看起来很像它代表一个响应对象,但事实并非如此。这是reply()
接口。应答接口实际上返回一个响应对象(如我的回答所示),该对象具有用于设置内容类型等的方法。