I understand that you can serve static content over express with:
app.use(express.static(__dirname + "../../../public_html"));
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.
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;
}
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.
Is there a better way to do this?
You can just use
res.format
to do the same thing. The example from the express docs:You can read more about it here: http://expressjs.com/en/api.html#res.format
You're on the right track. Here's a nice example from Express about using req.accept:
Updated:
You can use res.send to send files without rendering: