构建Django Rest框架。当我使用“ curl”用户使用有效令牌调用API时,它会起作用:

curl -viL -H "Authorization: Token 65c38dfe0c910b727197683aebdcc1c67c1b7aa3" http://127.0.0.1:8000/api/habit/


通过我的javascript调用进行的同一API调用失败,并且Django将其视为匿名用户并出错。

fetchHabits: function() {
  console.log('Token '+this.authToken.token);
  fetch('http://127.0.0.1:8000/api/habit/?format=json',{
     method: 'GET',
     headers: {
       'Accept': 'application/json',
       'Content-Type': 'application/json',
       'Authorization': 'Token '+this.authToken.token
     }
  })
  .then(response => response.json())
  .then(json => this.habits = json)
},


我已经证明正确的令牌已发送和接收。我假设是因为CURL可以正常工作,而Django代码也可以正常工作,因此该错误位于Javascript端的标头中。

有人可以帮忙吗?

最佳答案

HTTP标头中缺少一个组件,它需要具有“凭据:'included'”
最终标题为:

  fetch('http://127.0.0.1:8000/api/habit/?format=json',{
     method: 'GET',
     headers: {
       'Accept': '*/*',
       'Content-Type': 'application/json',
       'Authorization': 'Token '+this.authToken.token
     },
     credentials: 'include'
  })

关于javascript - 我是否具有完整的HTTP header 以正确进行身份验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45102382/

10-12 15:19