node.js - 提供多种内容类型

标签 node.js express url-routing

我正在使用 Express 创建网站和 API,我想在同一路径上提供多种内容类型(JSON、XML、HTML)。在 Express 中有没有更好的写法:

// 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>');
});

特别是,上面的代码看起来比较重复,可能有更标准的写法。

最佳答案

有一种 response.format 方法,它使用基于“接受” 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' });
  }
});

关于node.js - 提供多种内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23244174/

相关文章:

javascript - 有没有办法可以根据用户事件(例如评论)增加模型中的值?

asp.net-core - 在 ASP.NET Core 3.x MVC 中将 nameof() 与 Url.Action() 和异步方法一起使用

javascript - ReactJs 中的嵌套 URL 路由

node.js - SSL 安全连接是否可以在没有浏览器调用的情况下使用?

node.js - 在 NodeJs 中杀死由 spawn 触发的 FFmpeg 进程

node.js - 如何通过本地网络与 Electron/ express 应用程序共享数据?

Django url 反向错误

javascript - node.js promise 在 if 语句中没有解析

javascript - 如何在 JSDoc 中指定 promise 的解析和拒绝类型?

node.js - 如何在 Jest 中测试来自 Express 的响应数据