【问题标题】:how can I add CSRF token in VUE or reqwest?如何在 VUE 或 reqwest 中添加 CSRF 令牌?
【发布时间】:2018-09-22 03:52:13
【问题描述】:

当我向服务器发送数据时,服务器即使这样做也没有响应 如果 request.method == 'POST': print("************请求正文*******")

在 django views.py 中。这些代码不起作用。

enter code here

var app6 = new Vue({
  el: '#app-6',
  data: {
     realtimecost:0,
  },
  created() {            
        setInterval(() =>
        {
             this.realtimecost=this.realtimecost+1;           
             if(this.realtimecost==5)
                this.sendData();// here 

          }, 1000);
  },
  methods: {  
    sendData:function ()//send data
     {
        var self = this;
        reqwest({
        url:'http://127.0.0.1:8000/tasks/',
        method:'post', 
        type:'json',
        headers: {
         "X-CSRFToken": Cookies.get('csrftoken')
            },
        data:
        {
              realtimecost:5,
        },//end data
         success:function(resp){

         //self.getData()
         }//end success
        })//end reqwest
        },//end senddata

  }//end method

})//end app6

【问题讨论】:

  • 我没有使用过这个 http 库,但我可以看到它缺少拦截器,所以你可能需要在每个请求中发送带有 headers 对象的 csrf。 headers: { 'X-CSRF-TOKEN': token_here } - 将此属性传递给请求对象。
  • 我添加了 headers: { "X-CSRFToken": Cookies.get('csrftoken') },但是服务器仍然没有得到任何响应,即使像这个 elif request.method == 'POST' : print("************请求正文*******") 不能工作
  • 您是否更改了 csrf 令牌标头名称,或者您将其保留为默认名称?
  • 是的。 Cookies.get('csrftoken') 不起作用。它与形式上的 {% csrf_token %} 有关系吗?

标签: django vue.js csrf reqwest


【解决方案1】:

也许我在 web body 的表单中使用了 {% csrf_token %},所以 "X-CSRFToken": Cookies.get('csrftoken') 不能工作。

最后我将 "X-CSRFToken":'{{ csrf_token }}' 放在标题中并且它可以工作。但我不知道它的机制。

reqwest({
        url:'http://127.0.0.1:8000/tasks/',
        method:'post', 
        type:'json',
        headers: {
         "X-CSRFToken":'{{ csrf_token }}'
            },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2016-09-19
    • 2018-09-15
    相关资源
    最近更新 更多