node.js - 基于带有 express 的 "Accept" header 的网页有条件服务?

标签 node.js express http-headers

我知道您可以通过 express 提供静态内容:

app.use(express.static(__dirname + "../../../public_html"));

但是,我正在尝试根据响应发送过来的“接受” header 来明确更改它提供的内容的呈现方式。通常,我所拥有的内容是通过 REST API 以 JSON 格式请求的,因此 url 是:http://blah.com/this/that/item 并且效果很好。

但是,我也希望用户能够从浏览器访问同一页面,该浏览器会发送类似以下内容的内容:Accept:text/html 并且由于该 header ,请参阅页面使用正确的格式(CSS/JS/HTML/等)呈现相同的信息。

现在,我正在尝试通过以下方式提供内容:

if (req.accepts("text/html")) {
   res.sendfile("/", {
      root: "../../../public_html"
   });
   res.status(200);
   return;
}

其中 public_html 包含 index.html 以及与 CSS 和 JS 相关的目录。完成后我不会发送该文件,但我认为这将是一个好的开始,然后在我弄清楚如何基于 Accept header 提供静态内容后添加 JSON 内容。

有更好的方法吗?

最佳答案

您走在正确的轨道上。这是一个不错的 example来自 Express 关于使用 req.accept:

app.use(function(req, res, next){
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // respond with json
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});

更新:

您可以使用 res.send 发送文件而不渲染:

res.set('Content-Type', 'text/html');
res.send(new Buffer(fs.readFile(__dirname + 'index.html'));

关于node.js - 基于带有 express 的 "Accept" header 的网页有条件服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23351940/

相关文章:

javascript - 如何格式化此关联获取 Sequelize

node.js - 如何让 VSCode 运行像 "npm start"这样的 Node 应用程序?

javascript - 查询修饰符中出现意外标记 ":"

apache - 如何对apache header进行base64编码?

redirect - 当 url 没有尾部斜杠时,AWS s3 强制 302 重定向 - 需要 301s

javascript - 如何处理查询中的数组值?

node.js - 在express中正确使用app.set?

express - 如何为 webpack 模板添加后端?

JavaScript - 如何为浏览器 GET 设置请求 header

javascript - 什么函数被放入 Node Js 和 JS 的事件循环中