Liondalan
Liondalan

Reputation: 67

Laravel 8 API returns HTML instead of JSON

I'm working on a simple website in Laravel and Vue, code is running in Homestead. When the user visits the home page of the website, videos are being displayed in a grid. So API is called to fetch data and the return I get is an HTML of a .view file instead of JSON.

// API Routes in Api.php
Route::get('/videos', [VideoController::class, 'getVideos']);
Route::get('/videos/{id}', [VideoController::class, 'getVideo']);
Route::post('/user/login', [AuthController::class, 'login']);
Route::post('/user/check', [UserController::class, 'checkUser']);

// Controller function that returns data from website via ORM
public function getVideos(): JsonResponse{
    return resonse()->json([
        "response" => Video::all()
    ]);
}

Response in the console I get when API is being called enter image description here

Php artisan route:list enter image description here

Upvotes: 1

Views: 8811

Answers (2)

ceexon
ceexon

Reputation: 835

I had this issue and it was triggered by a middleware I created to check for some user info on every refresh.

Livewire sends a request to the backend for all bound attribute changes. The request would hit my middleware and I'd get a redirect to the target page.

In my case this only happened during onboarding cuz it's when I was checking if my user had the info. I just prevented all livewire requests from accessing this middleware and this was sorted out.

MyMiddleware.php

....
public function handle(Request $request, Closure $next): Response
{
   
  if (!str_contains($request->path(), 'livewire')) {
      // you can prevent specific routes if you wish, this is general

      if(my_condition_is_true){
          return redirect('/just/go/there')
      }
  }

   return $next($request);
}

Upvotes: 0

Ifeoluwa Adewunmi
Ifeoluwa Adewunmi

Reputation: 71

If I get your question correctly, your response is rendering Html instead of JSON?

You can create a global JsonMiddleware that accepts headers as application/json. To do this follow the following steps:

Step 1: create a new middleware

php artisan make:middleware JsonMiddleware

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

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

Your end 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\JsonMiddleware::class,
    // Other Middleware::class comes after...
];

Step 4: clear the application config cache and dump autoload

php artisan config:cache or composer dump-autoload

I hope this is helpful. Thanks.

Upvotes: 6

Related Questions