【问题标题】:Laravel fallback route always returning view instead of Json responseLaravel 后备路由总是返回视图而不是 Json 响应
【发布时间】:2019-09-01 18:36:05
【问题描述】:

使用 Laravel 构建 REST API。当客户端遇到不存在的路由时,我想返回一条 JSON 消息。

我有以下 api.php 文件:

<?php

use Illuminate\Http\Request;

Route::get('/', 'ListingController@getListingsAll')->name('all');


// No Authenticated Routes

Route::group(['prefix' => 'auth'], function () {
    Route::post('login', 'AuthController@login')->name('login');
    Route::post('register', 'AuthController@register')->name('register');
});

// Authenticated Routes

Route::group(['middleware' => 'auth:api'], function () {
    //Auth functions
    Route::group(['prefix' => 'auth'], function () {
        Route::get('logout', 'AuthController@logout');
        Route::get('user', 'AuthController@user');
    });

    //Listings

    Route::get('listings/user', 'ListingController@getListingsPerUser')->name('listings.user');
    Route::get('listings/all', 'ListingController@getListingsAll')->name('listings.all');
    ...
    ...
});


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

每当我对 http://localhost:8000/foohttp://localhost:8000/api/foo 等执行 REST 调用时...它都会返回 404 Not found Blade 视图而不是 JSON 响应。

有什么想法吗?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    最好在异常处理程序中实现这个

    App\Exceptions\Handler.php

    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    
    class Handler extends ExceptionHandler
    {
        public function render($request, Exception $exception)
        {
            if ($exception instanceof NotFoundHttpException) {
                return response(['status' => 'Not Found'], 404);
            }
            return parent::render($request, $exception);
        }
    }
    

    【讨论】:

    • 感谢这项工作。其实我之前试过,但是忘记加use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;。没有它,事情就无法运作。感谢您的帮助!
    猜你喜欢
    • 2021-03-08
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2022-10-20
    • 2020-04-25
    相关资源
    最近更新 更多