尝试从Aurelia JS文件进行Django API调用时出现禁止错误

时间:2019-02-12 11:59:30

标签: django aurelia

我已经将aurelia js集成到了django项目中,从aurelia中我试图使用django api,但是CSRF问题来了,我无法获得结果。

如果我正在django中创建普通的js文件,并从那里调用django api,则它可以工作,但是如果aurelia不能工作。 我的代码是:

import {inject,DOM, autoinject} from 'aurelia-framework';
import {HttpClient, json} from 'aurelia-fetch-client';

let httpClient = new HttpClient();
let tableHeading;

export class App {

    attached(){
        httpClient.fetch('/demographs/', {
            method: "POST",
            headers: {
                "X-CSRF-Token": this.getCookie("csrftoken"),
                "Accept": "application/json",
                'Cache': 'no-cache',
                "Content-Type": "application/json",
                'Cookie': 'csrftoken='+this.getCookie("csrftoken")
            },
            credentials: 'include'
        })
        .then(response => response.json())
        .then(data => {
            if(data && data.table && data.table.length) {
                tableHeading = data.table[0];
            }
        });
    }

    getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie != '') {
            let cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                let cookie = cookies[i].trim();

                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length +1));
                    break;
                }
            }
        }

        return cookieValue;
    }
}

0 个答案:

没有答案