3

在 Vue.js 项目中,我怎样才能获得csrftoken?

我试过使用js-cookie,但无法得到它:

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 '

}

但我可以得到其他饼干。


编辑

Cookies.get('csrftoken')

这段代码得到undefined

但是当我访问时,有csrftoken.

在此处输入图像描述

4

2 回答 2

1
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');

从 cookie 中获取 csrf:

 function getCookie(name)
  {
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return (value != null) ? unescape(value[1]) : null;
  }
于 2018-03-16T05:00:54.037 回答
1

您是否尝试过在服务器级别的 DOM 中简单地打印它。从那里得到它。Laravel 就是一个很好的例子:

https://laravel.com/docs/5.6/csrf#csrf-x-xsrf-token

<meta name="csrf-token" content="{{ csrf_token() }}">

当然替换{{ csrf_token() }}为您的服务器语言和 CSRF 令牌。

在你的 JS 中:

config.headers['x-csrftoken']=  $('meta[name="csrf-token"]').attr('content')

如果使用 jQuery。

于 2018-03-16T10:28:08.493 回答