根据要求提供JSON或HTML服务? [英] Serve either JSON or HTML based on what was requested?

查看:57
本文介绍了根据要求提供JSON或HTML服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是nodejs,我想创建一个统一的处理程序,以根据客户端请求的JSON或HTML格式提供服务.

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(...

但不是在请求主体中传递变量,而是在标头中包含某些内容,或者在 jQuery.getJSON() jQuery.get()之间存在本质上的区别我用来区分吗?

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?

推荐答案

是的,更好的方法是简单地检查请求的 Accept 标头.例如,如果标题显示:

Yes, a better way is to simply check the Accept header of the request. For example, if the header says:

Accept: application/json

然后再发送回JSON是适当的.例如,

then it is appropriate to send JSON back. Or for example,

Accept: text/html

然后您发送回html.

then you send back html.

这篇关于根据要求提供JSON或HTML服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆