node.js - Conditional serving of web pages based on "Accept" header with express? -
I understand that you can provide static content on expression:
App Express.static (__dirname + "../../../public_html"));
However, I am trying to express the presentation of content that sends it on the basis of the "accept" header, to which the response is sent. Generally, I have a content that is requested in a JSON format via the REST API so that the url is: http://blah.com/this/that/item
and this is good Works the way.
However, I would also like to have this enabled for users to access that page from a browser, which sends something like: Accept: text / html
And the page with the correct formatting (CSS / JS / HTML / etc) to present the same information due to that header.
Right now, I am trying to serve the content through this:
if (Req.accepts ("text / html")) {res.sendfile ("/", {Root: "../../../public_html"}); Res.status (200); Return; }
where public_html
holds index.html
and the directory related to CSS and JS. Whenever it is finished I will not send that file, but I thought it would be a good start and after that I will know how the static content is provided based on the acceptable header.
Is there a better way to do this?
You're on the right track about using Req.accept is better than Express:
app.use (function (req, res, next) respond to {res.status (404); // html page (req .accepts ('html')) {res.render Answer ('404', {url: req.url}); return;} with json if (req.accepts ('json')) {res.send ({Error: 'not found'}); Return;} // default to plain-text. Send () res.type ('txt'). Send ('not found');}); You can use res.send to send files without rendering: res .set ('content-type', 'text / html'); Res.send (new buffer (fs.readFile (__dynamic + 'index.html'));
Comments
Post a Comment