Reputation: 67
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
Upvotes: 1
Views: 8811
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
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:
php artisan make:middleware JsonMiddleware
$request->headers->set("Accept", "application/json");
public function handle(Request $request, Closure $next)
{
$request->headers->set("Accept", "application/json");
return $next($request);
}
protected $middleware = [
\App\Http\Middleware\JsonMiddleware::class,
// Other Middleware::class comes after...
];
php artisan config:cache or composer dump-autoload
I hope this is helpful. Thanks.
Upvotes: 6