My POST ajax request returns 302 on a Laravel Controller

7.7k views Asked by At

I send a POST Ajax request to a Laravel Controller but I get a 302 Found response code.

The controller is the ForgotPasswordController provided by Laravel's Auth package, so nothing special about it.

It has the guest middleware in its constructor and I found that if I remove this middleware from the constructor, the Ajax request works correctly (it returns a 200 response code).

The Ajax request has the X-CSRF-TOKEN and X-XSRF-TOKEN headers, so I don't think there is something missing.

I'm sending this Ajax request from a VueJS password reset form with the Axios library.

Why my POST request does not work if the controller has the guest middleware ?

Here are the headers sent with the request :

POST /password/email HTTP/1.1  
Host: myapp.dev  
Connection: keep-alive  
Content-Length: 37  
Pragma: no-cache  
Cache-Control: no-cache  
Origin: http://myapp.dev  
X-XSRF-TOKEN: eyJpdiI6IjRqTk1yTXFsXC9FVlRzckF0dUM4azdRPT0iLCJ2YWx1ZSI6IjY0MUZzaEpCTXJDcUhzUGhcL2dzYVJmalQrR3pwV3IzYWxiTSt4dVwvN2VVKzJ4b2t3XC9GcVhJcllmK3pQYVV4VGFIZG4wZ0s3NlNCTG01WEl6YzBCY2NRPT0iLCJtYWMiOiIwYmNjOTRiZGJjZTM2YjYyMWJiMzRhNTlkOTkwOWU4Y2M4NmYzYzI5NjhiMTU4MDdiMGJkMmJhYmMwODEzMDhjIn0=  
X-CSRF-TOKEN: nejsetydvFWgeqppZc5XQtX04b5AdXlsTKSgaydj  
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)  
 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Content-Type: application/json;charset=UTF-8  
Accept: application/json, text/plain, */*  
X-Requested-With: XMLHttpRequest  
Referer: http://myapp.dev/password  
Accept-Encoding: gzip, deflate  
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4  
Cookie: XSRF-TOKEN=eyJpdiI6IjRqTk1yTXFsXC9FVlRzckF0dUM4azdRPT0iLCJ2YWx1ZSI6IjY0MUZzaEpCTXJDcUhzUGhcL2dzYVJmalQrR3pwV3IzYWxiTSt4dVwvN2VVKzJ4b2t3XC9GcVhJcllmK3pQYVV4VGFIZG4wZ0s3NlNCTG01WEl6YzBCY2NRPT0iLCJtYWMiOiIwYmNjOTRiZGJjZTM2YjYyMWJiMzRhNTlkOTkwOWU4Y2M4NmYzYzI5NjhiMTU4MDdiMGJkMmJhYmMwODEzMDhjIn0%3D; laravel_session=eyJpdiI6IkJnczRHV3NcLzhLbzZWaUlvTTI2cFlBPT0iLCJ2YWx1ZSI6IkpQYytLXC9pQ1R3MTZlaEx2QWJ4bGpSd21BV25jelJKVDJkQVdcL25GSG4rQkpQc1duZHIrTjErOGt3bk5BVVVcL3FTK1c2XC83Y1NqTmxBaVZ1bkQ2TWV5Zz09IiwibWFjIjoiNzg4Y2UyNWQ0ODcxMWNkNWE3MmU4ZDY1MmIyNTE0NDgwMzFmM2ZjYzkxMzM5ZGM5ZTk5MDI4NjE4OGRkNmJjYyJ9
3

There are 3 answers

1
bhill77 On

302 response usually because your request is redirected by laravel. if you expect json response don't forget to add Accept: 'application/json' on your header request then you will see what actually wrong

2
Alex Slipknot On

You have to look closer into your controller. You have to return json. Also take a look in the network console in the browser. If response code is 302 there is a location. So if a location is the login page - validation not passed in the middleware

0
superfive33 On

Ok i found... it's just that I was authenticated when doing these requests. So the guest middleware was redirecting me... shame on me !