Serve either JSON or HTML based on what was reques

2019-07-31 03:07发布

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条回答
仙女界的扛把子
2楼-- · 2019-07-31 03:34

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.

查看更多
登录 后发表回答