Laravel如何知道Request :: wantsJson是JSON的请求? [英] How does Laravel know Request::wantsJson is a request for JSON?

查看:461
本文介绍了Laravel如何知道Request :: wantsJson是JSON的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到Laravel有一个整洁的方法 Request::wantsJson -我假设在发出请求时我可以传递信息请求JSON响应,但是我该怎么做,Laravel使用什么条件来检测请求是否要求JSON?

I noticed that Laravel has a neat method Request::wantsJson - I assume when I make the request I can pass information to request a JSON response, but how do I do this, and what criteria does Laravel use to detect whether a request asks for JSON ?

推荐答案

它使用客户端发送的Accept标头来确定是否需要JSON响应.

It uses the Accept header sent by the client to determine if it wants a JSON response.

让我们看一下代码:

Let's look at the code :

public function wantsJson() {
    $acceptable = $this->getAcceptableContentTypes();
    return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}

因此,如果客户端向application/json发送具有第一个可接受的内容类型的请求,则该方法将返回true.

So if the client sends a request with the first acceptable content type to application/json then the method will return true.

关于如何请求JSON,您应该相应地设置Accept标头,这取决于您用来查询路线的库,这是一些我知道的库示例:

As for how to request JSON, you should set the Accept header accordingly, it depends on what library you use to query your route, here are some examples with libraries I know :

枪口(PHP):

GuzzleHttp\get("http://laravel/route", ["headers" => ["Accept" => "application/json"]]);

cURL (PHP):

$curl = curl_init();
curl_setopt_array($curl, [CURLOPT_URL => "http://laravel/route", CURLOPT_HTTPHEADER => ["Accept" => "application/json"], CURLOPT_RETURNTRANSFER => true]);
curl_exec($curl);

请求(Python):

requests.get("http://laravel/route", headers={"Accept":"application/json"})

这篇关于Laravel如何知道Request :: wantsJson是JSON的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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