2016-12-16 155 views
0

我正在處理一個跟蹤待辦事項列表並將其從服務器中取出的站點。 下面有兩個示例ajax調用。任務GET調用工作正常,但是添加POST不。由於某種原因,它給了我一個403禁止的錯誤,因此,不執行代碼。通過ajax禁止服務器請求時出現錯誤403

我在看403 Forbidden error when making an ajax Post request in Django framework ,我讀了@yohn發佈的鏈接,但我不理解如何實現此解決方案。

var tasker = (function() { 
    return { 
     tasks : function(ownerId, cb) { 
      $.ajax({ 
       url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c", 
       type: 'GET', 
       success: function(task) { 
        if(task){ 
         var list = [] 
         for(var a=0; a<task.length; a++){     
          var newTask = { 
           onwerId: task[a].ownderId, 
           desc: task[a].desc, 
           due: new Date(task[a].due), 
           color: task[a].color, 
           complete: task[a].complete, 
           id: task[a].id 
          }; 
          list.push(newTask); 
         } 
         cb(list , null); 
        } 
        else{ cb(null, 'error retreiving your tasks');} 
       }, 
       error: function(xhr, status, errorThrown) { 
        alert("Sorry, there was a problem! " + errorThrown); 
       }, 
      });  
     }, 

     add : function(ownerId, task, cb) { 
      $.ajax({ 
       url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c", 
       type: 'POST', 
       success: function(task) { 
        var d = new Date(task.due); 
        if(task){ 
         var newTask = { 
          onwerId: task.ownderId, 
          desc: task.desc, 
          due: d, 
          color: task.color, 
          complete: task.complete, 
          id: task.id 
         }; 
         cb(newTask , null); 
        } 
        else{cb(null, 'error adding your task');} 
       }, 
       error: function(xhr, status, errorThrown) { 
        alert("Sorry, there was a problem! " + errorThrown); 
       }, 
      });    
     }, 
    }  

})(); 

回答

1

的Django使POST請求時(除非您使用的是基於令牌身份驗證,但我假設你是不是在這裏)需要csrf令牌。這就像你需要在表單提交中包含{{ csrf_token }}一樣。

有關爲什麼需要它和CSRF令牌的更多信息之目的:What is a CSRF token ? What is its importance and how does it work?

因此,對於你的問題,add下改變你的AJAX調用此:

$.ajax({ 
     url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c", 
     type: 'POST', 
     data: { csrfmiddlewaretoken: '{{ csrf_token }}'}, // added csrf token. 
     success: function(task) { 
      var d = new Date(task.due); 
      if(task){ 
       var newTask = { 
        onwerId: task.ownderId, 
        desc: task.desc, 
        due: d, 
        color: task.color, 
        complete: task.complete, 
        id: task.id 
       }; 
       cb(newTask , null); 
      } 
      else{cb(null, 'error adding your task');} 
     }, 
     error: function(xhr, status, errorThrown) { 
      alert("Sorry, there was a problem! " + errorThrown); 
     }, 
    }); 
相關問題