Serve either JSON or HTML based on what was requested?

落爺英雄遲暮 提交于 2020-01-16 04:55:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!