2
votes

I'm using laravel 5.6 with axios and vue for my SPA web app. the problem is after a while the csrf token will expire so there should be an annoying prompt telling the user to refresh the page which is not what I'm looking for. so all I know about csrf token in laravel 5.6 is it's used in bootstrap.js in this way:

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
   window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
  console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x- 
  csrf-token');
}

how I change this to get the csrf token on each request?

1
The accepted answer to this question seems to be a decent implementation you could adopt to solve your problem: stackoverflow.com/questions/31449434/… - matpb

1 Answers

3
votes

create an endpoint for retrieving the latest csrf token:

ExampleController.php

public function getCsrf() {
  return response(csrf_token());
}

Route: (routes/wew.php)

Route::get('csrf', 'ExampleController@getCsrf');

In your Javascript, you can request for a new csrf token and replace the old one in your axios instance.

axios.get('/csrf').then(({ data }) => {
  window.axios.defaults.headers.common['X-CSRF-TOKEN'] = data;
})