在配置axios的时候,怎么才能获取到Cookies中的`csrftoken`?

配置Axios.interceptors.request的时候:

Axios.interceptors.request.use(
  config => {

    if (
      config.method === "post" ||
      config.method === "put" ||
      config.method === "delete"||
      config.method === "get"
    ) {

    }


    if (Cookies.get('token')!==undefined) {   
      config.headers['Authorization']= 'Token '+Cookies.get('token');
    }
    // 这里我想在Cookies中得到 `csrftoken`,但是会直接跳过,得不到 
    if (Cookies.get('csrftoken')!==undefined) {   

      config.headers['x-csrftoken']= Cookies.get('csrftoken');  // 'CSRFToken'
    }

    return config;
  },
  error => {  
    return Promise.reject(error.data.error.message);
  }
);

但是释放断点之后,我们可以看到在请求头的Cookie上面有csrftoken

图片描述

我的AxiosConfig代码:

AxiosConfig:{
    baseURL: 'http://10.10.10.105:8001/',

    responseType: "json",
    withCredentials: true,  // 这里将会发送 Cookie (with it there are: sessionid, csrftoken)

    xsrfCookieName: 'csrftoken',  // default: XSRF-TOKEN
    xsrfHeaderName: 'x-csrftoken',   // default: X-XSRF-TOKEN
    headers: {
      "Content-Type": "application/json;charset=utf-8"
    }
  }

是不是与withCredentials: true有关系呢?

阅读 11.8k
4 个回答

你只能获取当前域名下的cookie,跨域获取不了的

如果写入的cookie没有被设置httpOnly,你在本地chrome devtool -> Application -> Cookies 里面是可以看到cookie的,此时,cookie是可以通过document.cookie读取到的。

新手上路,请多包涵

同遇到这个问题了。。好揪心。。。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题