问题
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?
回答1:
Yes, a better way is to simply check the Accept
header of the request. For example, if the header says:
Accept: application/json
then it is appropriate to send JSON back. Or for example,
Accept: text/html
then you send back html.
来源:https://stackoverflow.com/questions/26199609/serve-either-json-or-html-based-on-what-was-requested