DEV Community

Ifeoluwa Adewunmi
Ifeoluwa Adewunmi

Posted on • Updated on

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 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\JsonRequestMiddleware::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.

Top comments (7)

Collapse
 
kishita7 profile image
Kishita Variya • Edited

"Since I won't be using the web route so I decided to create a global JsonRequestMiddleware.... " It works great even when the app has web route (it does not affect the web route) - IFF you add it to protected

 $middlewareGroups = [
    'api' => [
// here
    ],
] 
Enter fullscreen mode Exit fullscreen mode

instead of $middleware in the Kernel.php file

Collapse
 
ife_adewunmi profile image
Ifeoluwa Adewunmi

Thank you for your feedback

Collapse
 
martinsonuoha profile image
Martins Onuoha

Shouldn't this \App\Http\Middleware\JsonMiddleware::class, be \App\Http\Middleware\JsonRequestMiddleware::class instead?

Collapse
 
ife_adewunmi profile image
Ifeoluwa Adewunmi

That's a very good observation from you, I have updated that. Thank you so much.

Collapse
 
elijahndege profile image
Elijah Ndege

This was really helpful. Saved me a lot

Collapse
 
ife_adewunmi profile image
Ifeoluwa Adewunmi

Thank you for your feedback

Collapse
 
martinsonuoha profile image
Info Comment hidden by post author - thread only accessible via permalink
Martins Onuoha

Shouldn't this \App\Http\Middleware\JsonMiddleware::class be \App\Http\Middleware\JsonRequestMiddleware::class instead?

Some comments have been hidden by the post's author - find out more