1

I use Django Rest framework session authentication,after user logged in I can do successful POST request (/api/post/1/like/) using browsable API.

Why can't I post using axios ? (user instance is must for Django server to save the above API )

I hope POST signal may not know logged in user even though I am loggedin as admin user

AXIOS FUNCTION

const likebutton = (id)=>{
           axios.post(`/api/post/${id}/like/`)         
    }

ERROR

Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:61)
Anoop K George
  • 1,605
  • 12
  • 40

1 Answers1

3

From django docs you can obtain the csrftoken with the following script:

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 = 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;
}
var csrftoken = getCookie('csrftoken');

Or, by using Javascript Cookie Library:

var csrftoken = Cookies.get('csrftoken');

Then, all you have to do is to update your axios call to send it as a header:

const likebutton = (id) => {
    axios.post(`/api/post/${id}/like/`, { headers: { 'X-CSRFToken': csrftoken } })
}
Bernardo Duarte
  • 4,074
  • 4
  • 19
  • 34