Conditional feed based on Accept header with expression?

I understand that you can use static content for expression with:

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

However, I am trying to express changes in the presentation of the content it contains based on the Accept header to which the response is sent. Usually the content that I have is requested in JSON format via the REST API, so the url is: http://blah.com/this/that/item and this works well.

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

Now I'm trying to transfer content through:

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

Where public_html contains index.html and relative directories with CSS and JS. I will not send this file when it is completed, but I decided that it would be a good start, and then add the JSON content after I figure out how to serve static content based on the Accept header.

Is there a better way to do this?

+7
source share
2 answers

You are on the right track. Here is a good 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'); }); 

Updated:

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')); 
+10
source share

You can simply use res.format to do the same. Example from express documents:

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

You can read more about this here: http://expressjs.com/en/api.html#res.format

+9
source share

All Articles