Home > Software engineering >  XMLHttpRequest not sending token (Laravel page expired)
XMLHttpRequest not sending token (Laravel page expired)

Time:03-17

I'm using Laravel and trying to send a form via XMLHttpRequest. It works but the request in the controller doesn't identify it as ajax. The form has a csrf input.

I've tried several things, right now my code looks like:

...
XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XHR.setRequestHeader("X-CSRFToken", FD.get("_token"));
...

But Laravel keeps sending a 419 | Page Expired response.

Maybe I'm misinterpreting this information, barking at the wrong tree, or I'm missing something here.

CodePudding user response:

Try to add X-Requested-With header to your request and change your content header to multipart or json :

XHR.setRequestHeader("X-Requested-With", 'XMLHttpRequest');
XHR.setRequestHeader("Content-type", 'multipart/form-data'); // or application/json
XHR.setRequestHeader("X-CSRF-Token", FD.get("_token"));
  • Related