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

I created a dribble clone using Laravel 8 and Nuxt.js. Since I won't be using the web route, 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

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");

Your result should look like this:

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

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

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

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


php artisan config:cache 
composer dump-autoload

Leave a comment if you've got a better way of achieving this. Kindly hit the like button if you find this is helpful.