Angular ngCookies $ cookie未定义

时间:2016-05-31 16:37:25

标签: angularjs django post csrf

我正在开发一个Django-Angular应用程序,并且需要使它成为所有Angular AJAX post或put请求中的csrf标记。我正在使用ngCookies,但是当我尝试将cookie csrf标记分配给所有角度标题时,它给了我一个错误:

TypeError: Cannot read property 'csrftoken' of undefined

$ cookieStore也是未定义的,并且在$ cookies上使用get方法也不起作用。我正在加载角度cookie的正确脚本,与我的角度版本匹配,我没有得到关于ngCookies本身的任何错误,所以我不确定它可能是什么?

(function () {
    'use strict';

Config.$inject = ["$locationProvider", "$stateProvider", "$urlRouterProvider", "$httpProvider"];
angular
    .module('app.guest', [
        'app.common',
        'app.core',
        'app.repo',
        'ui.bootstrap',
        'ngCookies'
    ])
    .config(Config);
    .run(['$cookies'], function ($rootScope, $http, $cookies) {
            // set the CSRF token here
            $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
        })

/** ngInject */
function Config($locationProvider, $stateProvider, $urlRouterProvider, $httpProvider, $cookies) {

    broadcastReady.$inject = ["CommonService", "CommonEvents"];
    $locationProvider.html5Mode(true);
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    $httpProvider.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;

控制台

vendor.js:12275 Uncaught Error: [$injector:modulerr] Failed to instantiate module app.guest due to:
TypeError: Cannot read property 'csrftoken' of undefined

1 个答案:

答案 0 :(得分:1)

"$cookies"列表的末尾添加$inject

Config.$inject = ["$locationProvider", "$stateProvider", "$urlRouterProvider", "$httpProvider", "$cookies"];

确保您也加载angular-cookies.js