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屋!