Heim  >  Artikel  >  Backend-Entwicklung  >  Laravel5.x如何让404返回一个json?

Laravel5.x如何让404返回一个json?

WBOY
WBOYOriginal
2016-06-06 20:31:561018Durchsuche

比如正常的一个请求,返回方式如下:

<code>return response($result, $code);  // 返回json
</code>

异常的请求,比如该路由没有被定义,该请求的方法没有被定义。如何也返回一个json对象呢,写在404.blade.php里肯定不合适,因为写进去的话会返回一个string

回复内容:

比如正常的一个请求,返回方式如下:

<code>return response($result, $code);  // 返回json
</code>

异常的请求,比如该路由没有被定义,该请求的方法没有被定义。如何也返回一个json对象呢,写在404.blade.php里肯定不合适,因为写进去的话会返回一个string

Middleware或者App\Exceptions\Handler里捕获
Symfony\Component\HttpKernel\Exception\NotFoundHttpException

如果是Middleware

<code>use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

public function handle($request, Closure $next) {
    try {
        return $next($request);
    } catch (NotFoundHttpException $e) {
        return response()->json(['msg'=>'NotFound']);
    }
}

</code>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn