AngularJS withCredentials

前端 未结 3 1280
失恋的感觉
失恋的感觉 2020-12-02 22:38

I\'ve been working on an AngularJS project which has to send AJAX calls to an restfull webservice. This webservice is on another domain so I had to enable cors on the server

相关标签:
3条回答
  • 2020-12-02 22:52

    In your app config function add this :

    $httpProvider.defaults.withCredentials = true;
    

    It will append this header for all your requests.

    Dont forget to inject $httpProvider

    EDIT : 2015-07-29

    Here is another solution :

    HttpIntercepter can be used for adding common headers as well as common parameters.

    Add this in your config :

    $httpProvider.interceptors.push('UtimfHttpIntercepter');

    and create factory with name UtimfHttpIntercepter

        angular.module('utimf.services', [])
        .factory('UtimfHttpIntercepter', UtimfHttpIntercepter)
    
        UtimfHttpIntercepter.$inject = ['$q'];
        function UtimfHttpIntercepter($q) {
        var authFactory = {};
    
        var _request = function (config) {
            config.headers = config.headers || {}; // change/add hearders
            config.data = config.data || {}; // change/add post data
            config.params = config.params || {}; //change/add querystring params            
    
            return config || $q.when(config);
        }
    
        var _requestError = function (rejection) {
            // handle if there is a request error
            return $q.reject(rejection);
        }
    
        var _response = function(response){
            // handle your response
            return response || $q.when(response);
        }
    
        var _responseError = function (rejection) {
            // handle if there is a request error
            return $q.reject(rejection);
        }
    
        authFactory.request = _request;
        authFactory.requestError = _requestError;
        authFactory.response = _response;
        authFactory.responseError = _responseError;
        return authFactory;
    }
    
    0 讨论(0)
  • 2020-12-02 23:00

    Clarification:

    $http.post(url, {withCredentials: true, ...}) 
    

    should be

    $http.post(url, data, {withCredentials: true, ...})
    

    as per https://docs.angularjs.org/api/ng/service/$http

    0 讨论(0)
  • 2020-12-02 23:12

    You should pass a configuration object, like so

    $http.post(url, {withCredentials: true, ...})
    

    or in older versions:

    $http({withCredentials: true, ...}).post(...)
    

    See also your other question.

    0 讨论(0)
提交回复
热议问题