【问题标题】:Rest API call returning forbiddenRest API 调用返回被禁止
【发布时间】:2021-05-03 12:46:20
【问题描述】:

我正在尝试通过调用 rest API 来获取一些数据,但它不工作并返回:

Forbidden: /api/networthchart/data/

我的视图/API 调用: (请忽略打印功能,我是用来测试的,但我把它们留在这里以防万一)

class networthChart(APIView, View):  
    authentication_classes = []
    permission_classes = []
    
    def get(self, request, format=None):
        print("its working")
        labels = []
        default_items = []

        if not self.request.user.is_active:
           return HttpResponseForbidden("Not signed in") # any error you want to display    
        else:
            print("user signed in")
            
        user = self.request.user
        networth_history = user.networthTracker.objects.filter(user = user)
        
        queryset = networth_history.order_by("date")
        print("questset gotten")
        
        for query in queryset:
            default_items.append(query.networth)
            labels.append(query.date)
            print("adding")
        
        print(labels)
        print(default_items)
        
        data = {
            "labels" : labels,
            "default" : default_items,
        }
        return Response(data)

JS 是:

<script>
$(document).ready(function(){
  var endpoint = '/api/networthchart/data/'
  var defaultData = []
  var labels = []
  
  $.ajax({
    method:"GET",
    url: endpoint,
    success: function(data){
      labels = data.labels
      defaultData = data.default
      var ctx = document.getElementById('myChart').getContext('2d');
      var myChart = new Chart(ctx, {
          type: 'bar',
          data: {
              labels: labels,
              datasets: [{
                  label: '# of Votes',
                  data: defaultData,
                 #there was other stuff in here like bg colour and but I removed it for the sake of saving your time.
      });
    },
    error: function(errordata){
        console.log(errordata)
    }
  })
}

})
</script>

如果您想了解有关错误的更多信息,它会说,

"GET /user/HTTP/1.1" 200 11730 它的工作 禁止:/api/networthchart/data/ [29/Jan/2021 20:42:39]“GET /api/networthchart/data/HTTP/1.1”403 13

我不明白为什么它被禁止,我应该怎么做才能使它工作?

给定的解决方案:

<script>
'X-CSRFToken': csrftoken
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

$(document).ready(function(){ ........

【问题讨论】:

  • 能否请您将完整的 URL 写入端点变量而不是 var endpoint = '/api/networthchart/data/
  • 这就是我在代码中写的全部内容,但是,如果您想知道完整的代码是 http:///user/api/networthchart/data/
  • 是的,试试完整的网址var endpoint = http://&lt;my localhost number thingy&gt;/user/api/networthchart/data/
  • 我试过了,它仍然不起作用,它仍然说,GET /api/networthchart/data/ HTTP/1.1" 403 13 它的工作

标签: django ajax django-rest-framework django-views


【解决方案1】:

响应是 403,因为 django 需要一个 csrf 令牌。在你的 JS 文件中添加数据

'X-CSRFToken': csrftoken
data: {
     'X-CSRFToken': csrftoken,
     labels: labels,
       datasets: [{
       label: '# of Votes',
       data: defaultData,
      }

csrftoken 在哪里

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

【讨论】:

  • 我已经发布了编辑后的代码,请检查一下,如果我做得对,请告诉我,顺便说一句,错误不多,数据仍然没有出来,但我会处理那,我不再得到错误。非常感谢您的宝贵时间,我真的很感激它并重视它,我保证将它传递下去:)
  • @Vardhan Mahajan 更新了我的代码。另外,您从哪里获取后端的数据?
猜你喜欢
  • 2017-12-01
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
相关资源
最近更新 更多