Node.js 如何使用node js express响应xml?
我想写一个函数,可以生成网站地图一样。这是我的密码Node.js 如何使用node js express响应xml?,node.js,xml,express,Node.js,Xml,Express,我想写一个函数,可以生成网站地图一样。这是我的密码 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
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
<?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>
然后我尝试使用:console.log(feed.end({pretty:true}))代码>
要查看发生了什么,我的控制台日志如下所示:
http://example.com/tag/Cookies 2 http://example.com/tag/Candy 1 http://example.com/tag/Chocolate 3
<?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>
http://example.com/tag/Cookies
2.
http://example.com/tag/Candy
1.
http://example.com/tag/Chocolate
3.
我怎样才能正确地解决这个问题呢?这可能是因为您使用的是默认的内容类型(可能是html),所以所有的标记都是隐藏的,因为它被定义为html
您需要先将内容类型设置为text/xml
res.header(“内容类型”、“文本/xml”);
返回res.status(200.send)(feed.end({pretty:true}));
这可能是因为您使用的是默认的内容类型(可能是html),所以所有标记都被隐藏,因为它被解释为html
您需要先将内容类型设置为text/xml
res.header(“内容类型”、“文本/xml”);
返回res.status(200.send)(feed.end({pretty:true}));
它成功了。我还没有设置内容类型。谢谢你,我工作得很好。我还没有设置内容类型。多谢各位