DEV Community

loading...

How To Solve Laravel 8 API Response that is returning welcome page instead of JSON

ife_adewunmi profile image Ifeoluwa Adewunmi ・1 min read

I created a dribble clone using Laravel 8 and Nuxt.js. Since I won't be using the web route so I decided to create a global JsonRequestMiddleware that accepts headers as application/json. This write-up aims to show you how I implemented that step by step. Happy reading
Step 1: create a new middleware

php artisan make:middleware JsonRequestMiddleware

Enter fullscreen mode Exit fullscreen mode

Step 2: Copy this code and place it inside the JsonRequestMiddleware at the handle method before 'return $next($request);'

$request->headers->set("Accept", "application/json");

Enter fullscreen mode Exit fullscreen mode

Your end result should look like this:

public function handle(Request $request, Closure $next)
{
    $request->headers->set("Accept", "application/json");
    return $next($request);
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Go to App\Http\Kernel.php file and add the code below at global HTTP middleware stack.

protected $middleware = [
    \App\Http\Middleware\JsonMiddleware::class,
    // Other Middleware::class comes after...
];

Enter fullscreen mode Exit fullscreen mode

Step 4: clear the application config cache and dump-autoload

php artisan config:cache or composer dump-autoload

Enter fullscreen mode Exit fullscreen mode

you can share with me if you have got a better way of achieving this. I hope this is helpful. Thanks.

Discussion (0)

pic
Editor guide