LoginSignup
3
1

More than 3 years have passed since last update.

Laravelでapiを叩いたときにjsonが返ってこない問題

Posted at

確認時のLaravelバージョンは7.26.1

apiを叩いたときにjsonが返ってこない問題

結論から言うとapiを叩く際に下記ヘッダーを付与しなければならない

Accept: application/json
or
X-Requested-With: XMLHttpRequest

個人的にはX-Requested-With: XMLHttpRequestで良いかと思います。view側でaxios使用時に使われているので

resources/js/bootstrap.js


window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

原因調べてみた

ソースを追っていくとHandler::expectsJsonがfalseになってしまうのが原因

1. app/Exceptions/Handler::render
2. vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler::render
3. vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler::expectsJson

Handler::expectsJsonの実装を見るとこんな感じ

    public function expectsJson()
    {
        return ($this->ajax() && ! $this->pjax() && $this->acceptsAnyContentType()) || $this->wantsJson();
    }

各メソッドを引っ張ってくるとこんな感じ


    public function ajax()
    {
        return $this->isXmlHttpRequest();
    }

    public function isXmlHttpRequest()
    {
        return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
    }

    public function pjax()
    {
        return $this->headers->get('X-PJAX') == true;
    }

    public function acceptsAnyContentType()
    {
        $acceptable = $this->getAcceptableContentTypes();

        return count($acceptable) === 0 || (
            isset($acceptable[0]) && ($acceptable[0] === '*/*' || $acceptable[0] === '*')
        );
    }

    public function getAcceptableContentTypes()
    {
        if (null !== $this->acceptableContentTypes) {
            return $this->acceptableContentTypes;
        }

        return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
    }

    public function wantsJson()
    {
        $acceptable = $this->getAcceptableContentTypes();

        return isset($acceptable[0]) && Str::contains($acceptable[0], ['/json', '+json']);
    }

これ外部のapiクライアント使った時のハマりポイントですね
公式ドキュメントに乗っけて欲しい。。。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1