Home > Software design >  How to debug unwanted 302 redirect from Ajax request?
How to debug unwanted 302 redirect from Ajax request?

Time:12-01

I'm trying to get data from a database through this ajax request:

axios.get('/about-info')

web.php:

Route::get('/about-info', [CMSController::class, 'aboutInfo']);

CMSController.php:

public function aboutInfo()
{
    $data = DB::table('about_info')->first('order by id desc');
    return $data;
}

but instead I am getting the whole welcome.blade.php content. It looks like the url in web.php is not called and instead a redirect happens. The dev tools network tab shows a 302 redirect.

This thread seems to have insight on this issue. I've been trying to implement answer 3 (adding accept: 'application/json to the config/headers object of the request) but the object already has that entry:

config:
    headers:
        Accept: "application/json, text/plain, */*"

This guide is talking about auth middleware being the possible cause of this problem but I'm not using middleware (at least none I am aware of). Any idea how to get to the root of this?

CodePudding user response:

Have you tried moving the route to your api routes file? All routes in the web namespace receive session state, CSFR, and possibly more that could be getting in the way (i.e. "new session, go to the welcome screen!").

This would change your URL path to:

axios.get('/api/about-info')

CodePudding user response:

Turns out that web.php was not working at all because of caching issues. Running:

php artisan route:clear

made it work again and showed every problem, which could not be detected before clearing the cache.

  • Related