Laravel API返回视图404错误而不是JSON错误

时间:2019-05-31 20:04:24

标签: laravel api

我正在尝试使用laravel创建RESTful API,我试图获取具有无效ID的资源,结果是404(因为找不到),但是我的问题是响应不是JSON格式,但使用HTML的View 404(默认情况下)。有什么方法可以将响应转换为JSON吗?对于这种情况,我使用Homestead。

我尝试添加一个后备路由,但似乎不适合这种情况。

Route::fallback(function () {
    return response()->json(['message' => 'Not Found.'], 404);
});

我尝试修改Handler(App \ Exceptions),但没有任何变化。

public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException) {
        if ($request->ajax()) {
            return response()->toJson([
                'message' => 'Not Found.',
            ], 404);
        }
    }

    return parent::render($request, $e);
}

3 个答案:

答案 0 :(得分:1)

您需要在请求中发送正确的Accept标头:'Accept':'application/json'

然后Illuminate\Foundation\Exceptions\Handler将在您的响应中使用render方法中的格式:

return $request->expectsJson()
                    ? $this->prepareJsonResponse($request, $e)
                    : $this->prepareResponse($request, $e);

答案 1 :(得分:0)

如果您的项目仅是RESTful API ,并且没有视图,则可以添加新的middleware,该['accept' => 'application/json']标头会添加到所有请求。这将确保所有响应都将返回json而不是视图

<?php

namespace App\Http\Middleware;

use Closure;

class AddAjaxHeader
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->headers->add(['accept' => 'application/json']);
        return $next($request);
    }
}

并将其添加到Kernel.php

答案 2 :(得分:-1)

     /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        switch (class_basename($exception)) {
            case 'NotFoundHttpException':
            case 'ModelNotFoundException':
                $exception = new NotFoundHttpException('Not found');
                break;
        }

        return parent::render($request, $exception);
    }