如何用nodejsexpress响应xml



我想写一个函数,可以生成类似https://www.bbc.co.uk/sitemap.xml.这是我的代码

module.exports.sitemapTag = async (req, res) => {
try {
const defaultPath = 'https://example.com/tag';
const tagList = [];
const data = { tags: await TagService.getAllTag() };
// eslint-disable-next-line no-restricted-syntax
for (const item of data.tags) {
const element = {
sitemap: {
tag: defaultPath.concat(item.tagText),
tagNum: item.tagNumber,
},
};
tagList.push(element);
}
const feed = xmlbuilder.create(tagList, { encoding: 'utf-8' });
return res.status(200).send(feed.end({ pretty: true }));
} catch (error) {
console.log(error);
return res.status(400).json(null);
}
};

但当我访问localhost://9191/api/v1/sitemapTag时,结果只是一个这样的字符串:

http://example.com/tag/Cookies 2 http://example.com/tag/Candy 1 http://example.com/tag/Chocolate 3

然后我尝试使用:console.log(feed.end({ pretty: true }));看看发生了什么,我的控制台日志是这样的:

<?xml version="1.0" encoding="utf-8"?>
<sitemap>
<tag>http://example.com/tag/Cookies</tag>
<tagNum>2</tagNum>
</sitemap>
<sitemap>
<tag>http://example.com/tag/Candy</tag>
<tagNum>1</tagNum>
</sitemap>
<sitemap>
<tag>http://example.com/tag/Chocolate</tag>
<tagNum>3</tagNum>
</sitemap>

我怎样才能正确地解决这个问题?

这可能是因为您使用默认的内容类型(可能是html(,所以所有标签都被隐藏,因为它被集成为html

在之前,您需要将内容类型设置为text/xml

res.header("Content-Type", "text/xml");
return res.status(200).send(feed.end({ pretty: true }));

最新更新