有条件的网页服务基于"接受"标题与快递?

zer*_*298 8 http-headers node.js express

我了解您可以通过以下方式提供静态内容:

app.use(express.static(__dirname + "../../../public_html"));
Run Code Online (Sandbox Code Playgroud)

但是,我试图根据响应发送的"Accept"标题明确更改它提供的内容的表示.通常,我通过REST API以JSON格式请求我拥有的内容,因此url是:http://blah.com/this/that/item并且运行良好.

但是,我还希望用户能够从浏览器访问同一页面,这将通过以下内容发送:Accept:text/html并且由于该标题,请查看具有正确格式(CSS/JS/HTML /等)的页面以呈现相同的信息.

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

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

public_html持有index.html与CSS和JS的相对目录.我不会在完成后发送该文件,但我认为这将是一个良好的开端,然后在我弄清楚如何基于Accept标头提供静态内容之后添加JSON内容.

有一个更好的方法吗?

Dan*_*ohn 15

你走在正确的轨道上.这是关于使用req.accept的Express 的一个很好的例子:

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');
});
Run Code Online (Sandbox Code Playgroud)

更新:

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

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


小智 12

你可以res.format用来做同样的事情.来自快递文档的示例:

res.format({
  text: function(){
    res.send('hey');
  },

  html: function(){
    res.send('<p>hey</p>');
  },

  json: function(){
    res.send({ message: 'hey' });
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以在这里阅读更多相关信息:http://expressjs.com/en/api.html#res.format