I'm using nodejs and I want to make a unified handler to serve either JSON or HTML based on which one was requested from the client.
So far I though of simply passing a variable in the request body that I can check before serving
app.use(function(req, res) {
if (req.body.requested=='JSON')
res.json(...
else
res.render(...
But instead of passing the variable in request body, is there something in the headers or something intrinsically different between jQuery.getJSON()
and jQuery.get()
that I use to make the differentiation?
Yes, a better way is to simply check the
Accept
header of the request. For example, if the header says:then it is appropriate to send JSON back. Or for example,
then you send back html.