简体   繁体   中英

Why do I keep getting 403 error in Django after using csrftoken in Ajax POST call?

I am doing an Ajax POST request to get news articles. I have put a csrftoken in the headers, but I still keep getting a 403 error. I have looked online and have tried many solutions, but I keep getting a 403 error. Why is this?

$('#search-articles').on('submit', function(event) {
      event.preventDefault();
      document.getElementById("loading").style.display = "block";
      document.getElementById("search-bar").style.display = "none";
      document.getElementById("articles").style.display = "none";
      
      function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // 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;
      }

      $.ajax({
        url: "{% url 'stocks_sites:get_news_articles' %}",
        type: "POST",
        data: {
          "q": document.getElementById("search-articles").value,
          csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
        },
        headers: {
          "X-CSRFToken": getCookie("csrftoken"),  // don't forget to include the 'getCookie' function
        },
        
        success: function(response) {
          document.getElementById("loading").style.display = "none";
          document.getElementById("search-bar").style.display = "block";
          document.getElementById("articles").style.display = "block";
          $("#search-bar").html(response[0]);             
          $("#articles").html(response[1]);

        }
      })
    })

try

     $.ajax({
        url: "{% url 'stocks_sites:get_news_articles' %}",
        type: "POST",
        data: {
          
          'csrfmiddlewaretoken': document.csrftoken,

        },
        
        
        success: function(response) {
          document.getElementById("loading").style.display = "none";
          document.getElementById("search-bar").style.display = "block";
          document.getElementById("articles").style.display = "block";
          $("#search-bar").html(response[0]);             
          $("#articles").html(response[1]);

        }
      })
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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