且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel-当API路由错误或找不到时如何显示JSON?

更新时间:2023-11-19 18:40:52

您应将设置为application/jsonAccept标头添加到标头选项卡中的邮递员请求中,如下所示::

You should add the Accept header set to application/json to your postman request in the headers tab like so: :

这将告诉Laravel您需要json响应,而不是HTML.对于您的应用程序中的任何请求,同样如此.

This will tell Laravel that you want a json response, instead of HTML. The same would apply for any request inside your application.

如您所见,在Illuminate\Http\Response对象上对此进行了检查,设置了有效负载后,它会检查是否应将其变形为JSON:

As you can see, this is checked on the Illuminate\Http\Response object, when the payload is set, it checks if it should be morphed to JSON:

/**
 * Set the content on the response.
 *
 * @param  mixed  $content
 * @return $this
 */
public function setContent($content)
{
    $this->original = $content;

    // If the content is "JSONable" we will set the appropriate header and convert
    // the content to JSON. This is useful when returning something like models
    // from routes that will be automatically transformed to their JSON form.
    if ($this->shouldBeJson($content)) {
        $this->header('Content-Type', 'application/json');

        $content = $this->morphToJson($content);
    }

    // If this content implements the "Renderable" interface then we will call the
    // render method on the object so we will avoid any "__toString" exceptions
    // that might be thrown and have their errors obscured by PHP's handling.
    elseif ($content instanceof Renderable) {
        $content = $content->render();
    }

    parent::setContent($content);

    return $this;
}

您可以在此处.

希望这对您有所帮助.