Laravel如何知道 Request::wantsJson 是 JSON 的请求?

2022-08-30 12:04:09

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


答案 1

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

让我们看一下代码

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

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

至于如何请求JSON,你应该相应地设置头,这取决于你用什么库来查询你的路由,以下是一些我知道的库的例子:Accept

咕噜咕噜(菲律宾比索):

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"})

答案 2

推荐