Search code examples
djangodjango-rest-frameworkdjango-cors-headers

CORS error when posting data to my DRF API from a template within the project itself


I have a Django project that has an end-point created using DRF. I am posting data to it from a template within the project itself (another rendered view). However, I get the following error code:

403 Unauthorized. CSRF token not provided.

This makes no sense because both the end-point and the view shares the same origin. So why am I getting this error? And how can I solve this issue? Thanks for any help.


Solution

  • You simply need to do what it says: provide csrf token. Use this function to get it from cookies:

    export function getCookie(name){
      let cookieValue = null;
      if (document.cookie && document.cookie !== '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = cookies[i].trim();
              if (cookie.substring(0, name.length + 1) === (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
    }
    

    Then modify your ajax function like so:

    const csrf_token = this.getCookie('csrftoken')
    const postData = async() => {
                  ... 
          headers: {
              'Content-Type': 'application/json',
              'x-csrftoken': csrf_token
          }
                  ...
    }