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

我明白,您可以通过以下方式提供静态内容:

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

但是,我试图根据响应发送的“接受”头来明确更改其提供的内容的呈现方式。 通常情况下,我所拥有的内容是通过REST API以JSON格式请求的,因此url是: http://blah.com/this/that/item : 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; } 

其中public_html保存index.html和与CSS和JS相关的目录。 我不会发送该文件,但是我认为这将是一个很好的开始,然后添加JSON内容后,我想出了如何提供基于Accept标头的静态内容。

有一个更好的方法吗?

你在正确的轨道上。 以下是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')); 

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

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

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