3

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

user7693832
  • 6,119
  • 19
  • 63
  • 114
  • I use the debugger, in there , I console the `document.cookie`, there is no `csrftoken` and `sessionid`, when I request a api, they will appear in the Cookie in the request header. – user7693832 Mar 16 '18 at 12:22

2 Answers2

1
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;
  }
Neha
  • 2,136
  • 5
  • 21
  • 50
1

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.

2Fwebd
  • 2,005
  • 2
  • 15
  • 17