user7693832
user7693832

Reputation: 6849

How to get `csrftoken` in Vue.js?

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.

enter image description here

Upvotes: 3

Views: 6352

Answers (2)

2Fwebd
2Fwebd

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

Neha
Neha

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

Related Questions