Laravel-当API路由错误或找不到时如何显示JSON? [英] Laravel - How to show JSON when API route is wrong or not found?
问题描述
我正在使用Laravel创建API,而邮递员正在检查我的API.当我在邮递员中输入正确的URL时,它工作正常,但是当我输入错误的URL时,它显示HTML和Laravel 404错误,我想返回JSON格式的消息,我该怎么做.
I am using Laravel to create API and postman to check my API. When I am putting a right URL in postman it is working fine, but when I am putting a wrong URL it is showing HTML and Laravel 404 error, I want to return a message in JSON format, how would I do that.
推荐答案
您应将设置为application/json
的Accept
标头添加到标头选项卡中的邮递员请求中,如下所示::
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;
}
您可以在此处.
希望这对您有所帮助.
这篇关于Laravel-当API路由错误或找不到时如何显示JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!