Not able to get data from backend api in django project


#1

Because django using Csrf middleware, because of that I am not able to hit api.
I am able to integrate aurelia with django,

this is my code:

 httpClient.fetch('http://localhost:8001/demographs/', {
  method: "POST"

})
.then(response => response.json())
.then(data => {
if(data && data.table && data.table.length) {
tableHeading = data.table[0];
console.log(“table data”,tableHeading);
}
});


#2

Can anyone help on this?


#3

Can you clarify what the error you are getting is?


#4

Hi @bigopon
This is the error I am getting,


#5

Sorry, I’m neither familiar with this, nor understand django to make a guess. I hope other folks with experience can help point you to the right direction.


#6

Print the CSRF token on your page into hidden input with Django and then set the header.
setRequestHeader(“X-CSRFToken”, csrftoken from the hidden input);
I believe this will work for you


#7

You may need to set an interceptor with CSRF Token header (django uses: “X-CSRFToken” header with each POST request).

There is also a CSRF cookie, which you first receive from csrftoken cookie

If you use aurelia-cookie I think you can do Cookie.get('csrftoken') – otherwise you may have to use Document.cookie.

if (document.cookie.split(';').filter((item) => item.trim().startsWith('csrftoken=')).length) {
    console.log('The cookie "reader" exists (ES6)')
}

THEN and only THEN can you set the header in interceptor using http-client configuration withInterceptor

Important NOTE:

HTTP AJAX calls with GET|HEAD|OPTIONS|TRACE does not require X-CSRFToken header.

Works the same with Python Flask although there’s not too many examples where it sets the cookie. But the trick is:

from flask_wtf.csrf import generate_csrf

@app.after_request
def add_csrf_token(response)
    response.headers.set('X-CSRFToken', generate_csrf())
    return response

In your after-request responses you can set a header for CSRF Tokens for Aurelia to extract it… Or you can set a cookie instead of a header to extract it from Aurelia.