基于“接受”的有条件的网页服务标题与快递? [英] Conditional serving of web pages based on "Accept" header with express?

查看:140
本文介绍了基于“接受”的有条件的网页服务标题与快递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I understand that you can serve static content over express with:

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

但是,我试图通过接受标题响应发送。通常,我通过REST API以JSON格式请求的内容,因此URL是: http://blah.com/this/that/item ,那很好,

However, I'm trying to have express change the presentation of the content it delivers based upon the "Accept" header the the response sends over. Normally, the content that I have is requested in a JSON format through a REST API so the url is: http://blah.com/this/that/item and that works well.

然而,我也希望用户能够从浏览器访问相同的页面,该浏览器将通过以下方式发送:接受:text / html 并且因为该标题,请查看格式正确的页面(CSS / JS / HTML / etc)来呈现相同的信息。

However, I would also like for users to be able to access that same page from a browser which would send over something like: Accept:text/html and because of that header, see a page with correct formatting (CSS/JS/HTML/etc) to present the same information.

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

Right now, I'm trying to serve the content through:

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

其中 public_html index.html 以及与CSS和JS相关的目录。我不会发送这个文件,只要这个完成,但我认为这将是一个好的开始,然后添加JSON内容,我想出了如何提供基于接受标题的静态内容。

Where public_html holds index.html and the relative directories with the CSS and JS. I won't send that file whenever this is finished, but I figured it would be a good start and then add the JSON content after I figured out how to serve static content based on the Accept header.

有更好的方法吗?

推荐答案

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

You're on the right track. Here's a nice example from Express about using 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发送文件而不呈现:

You can use res.send to send files without rendering:

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

这篇关于基于“接受”的有条件的网页服务标题与快递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆