node 返回 xml 格式文档的方法

栏目: NodeJs 发布时间:2024-11-01

背景

在某些特殊应用场景,比如网站地图 sitemap,我们需要返回 xml 格式的文档。

node 中如何将 xml 返回给客户端呢?

看下面这个 http 响应头信息,默认的 content-type(文档类型)为 text/html,要返回 xml,我们需要设置响应头,将 content-type 修改为 text/xml

Response Headers
  content-encoding: gzip
  content-type: text/html; charset=utf-8
  date: Wed, 11 Jan 2023 01:32:08 GMT
  proxy_headers: Host www.tides.cn,Real-IP 222.71.132.210,Proto https,For www.tides.cn
  server: nginx/1.14.1
  x-content-type-options: nosniff
  x-download-options: noopen
  x-frame-options: SAMEORIGIN
  x-readtime: 248
  x-xss-protection: 1; mode=block

eggjs 返回 xml

const Controller = require('egg').Controller;

class XmlController extends Controller {
  async index() {
    const { ctx } = this
    ctx.set('content-type', 'text/xml');
    await ctx.render('xml/tides.cn.ejs');
  }
}

module.exports = XmlController;

express 返回 xml

app.get('/tides.cn.xml', function(req, res){
    res.contentType('application/xml');
    res.sendFile('/tides.cn.xml');
});

以上就是 node 服务端返回 xml 的方法,祝你好运!

本文地址:https://www.tides.cn/p_node-set-res-content-type-xml