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

hmm*_*ead 7 laravel

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

我尝试包含一条后备路线,但它似乎不适合这种情况。

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

我尝试修改处理程序(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);
}
Run Code Online (Sandbox Code Playgroud)

Rah*_*hat 8

对于 Laravel 9

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
 
/**
 * Register the exception handling callbacks for the application.
 *
 * @return void
 */
public function register()
{
    $this->renderable(function (NotFoundHttpException $e, $request) {
        if ($request->is('api/*')) {
            return response()->json([
                'message' => 'Record not found.'
            ], 404);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 在应用程序/异常/Handler.php (2认同)

Ada*_*uez 2

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

然后将处理您的响应Illuminate\Foundation\Exceptions\Handler中方法的格式:render

return $request->expectsJson()
                    ? $this->prepareJsonResponse($request, $e)
                    : $this->prepareResponse($request, $e);
Run Code Online (Sandbox Code Playgroud)