简体   繁体   English

Rest API 禁止回拨

[英]Rest API call returning forbidden

I am trying to get some data by calling a rest API but it's not working and returning:我试图通过调用 rest API 来获取一些数据,但它不工作并返回:

Forbidden: /api.networthchart/data/

My view/API call: (Please ignore the print functions, I was using those for testing, but I left them in here just in case)我的视图/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)

and the JS is: 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>

If you want more info on the error, it says,如果您想了解有关错误的更多信息,它会说,

"GET /user/ HTTP/1.1" 200 11730 its working Forbidden: /api.networthchart/data/ [29/Jan/2021 20:42:39] "GET /api.networthchart/data/ HTTP/1.1" 403 13 “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

I don't understand why it's forbidden and what should I do to make this work?我不明白为什么它被禁止,我应该怎么做才能让它发挥作用?

The given solution:给出的解决方案:

<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(){ ........

The response is 403 because django requires a csrf token.响应为 403,因为 django 需要 csrf 令牌。 In your JS file data's add在你的 JS 文件数据中添加

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

where csrftoken is 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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM