Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional serving of web pages based on "Accept" header with express?

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?

like image 592
zero298 Avatar asked Apr 28 '14 22:04

zero298


People also ask

What is accept in HTTP header?

The Accept request HTTP header indicates which content types, expressed as MIME types, the client is able to understand. The server uses content negotiation to select one of the proposals and informs the client of the choice with the Content-Type response header.

What is Express JSON ()?

json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.

Which method will you use in your Express application to get JSON data from the client side?

body object allows you to access data in a string or JSON object from the client side.


1 Answers

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');
});

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'));
like image 196
Dan Kohn Avatar answered Sep 22 '22 05:09

Dan Kohn