【问题标题】:How to attach csrf header and value in axios POST request如何在 axios POST 请求中附加 csrf 标头和值
【发布时间】:2017-10-29 07:37:13
【问题描述】:

当用户使用提供的表单注册时,我需要发送 CSRF 令牌。

但是,由于注册/登录将是第一次与 django REST API 交互,所以我在加载网页时创建了一个虚拟 GET 请求以从 django 检索 CSRF 令牌。

令牌被检索并存储在 cookie 中。

但是,我仍然从 django 获得Forbidden (CSRF cookie not set.)

这是我的 axios POST 请求。

import axios from 'axios'
axios.defaults.xsrfCookieName = 'vcubes'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'

let req = {
    url: 'http://localhost:9000/vcubes/signup/',
    method : 'POST',
    headers: {
        'Content-Type': 'text/plain'
    },
    data: data
}

注意:

当我将withCredentials: true 添加到 axios POST 的标头中时,浏览器会发送 OPTIONS 请求而不是 POST。

【问题讨论】:

    标签: django csrf


    【解决方案1】:

    这是我在 django 中使用的:

    result = { "insert your key values here" }
    data = JSON.stringify(result)
    axios.post("{% url 'error_checking' %}", data, {headers: {'X-CSRFToken': '{{ csrf_token }}',}})
    

    【讨论】:

      【解决方案2】:
        let csrftoken = Vue.$cookies.get('vcubes')
      
        return axios.post('', data, {
          headers: {
            'X-CSRFToken': csrftoken
          }
        }).then(response => {
          return response.data
        })
      

      这与 Shane 的答案非常相似,但展示了如何在 Vue 中获取 csrf 令牌。如果您的问题是获取 cookie,那么this SO 答案应该对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2021-09-06
        • 2017-08-20
        • 2017-11-29
        • 1970-01-01
        • 2017-11-20
        • 2020-12-29
        • 2020-04-18
        • 2018-08-09
        • 2017-01-18
        相关资源
        最近更新 更多