Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
609 views
Welcome To Ask or Share your Answers For Others

1 Answer

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):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...