Reputation: 6849
In Vue.js project, how can I get the csrftoken
?
I tried use js-cookie
, but can not get it:
import Cookies from 'js-cookie';
if (Cookies.get('csrftoken')!==undefined) { // there will skip, because the Cookies.get('csrftoken') is undefined.
config.headers['x-csrftoken']= Cookies.get('csrftoken'); // 'CSRFToken '
}
but I can get other cookie.
EDIT
Cookies.get('csrftoken')
this code get undefined
.
But when I access, there is the csrftoken
.
Upvotes: 3
Views: 6352
Reputation: 2095
Have you tried to simply print it in the DOM on the server level. The get it from there. Laravel is a good example:
https://laravel.com/docs/5.6/csrf#csrf-x-xsrf-token
<meta name="csrf-token" content="{{ csrf_token() }}">
Of course replace {{ csrf_token() }}
with your server language and the CSRF token.
And in your JS:
config.headers['x-csrftoken']= $('meta[name="csrf-token"]').attr('content')
If using jQuery.
Upvotes: 1
Reputation: 2271
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
get csrf from cookies:
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
Upvotes: 1