How does Laravel know Request::wantsJson is a requ

2020-02-24 12:17发布

问题:

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 ?

回答1:

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';
}

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

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 :

Guzzle (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);

Requests (Python) :

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