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

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

php - How does Laravel know Request::wantsJson is a request for 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 ?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...