简体   繁体   中英

How to send header data in http request in Angular js

While trying to access a secured Api, I need to send header data with in my angular http requests

javascript code :

$http.post('http://localhost/api/validate', user).success(function () {
        $scope.reset();
        $scope.activePath = $location.path('/');

How to send header data with in this request?

   //store the header data in a variable 
    var headers = { 'Authorization': authToken };

    //Add headers with in your request
    $http.post('http://localhost/api/validate',user, { headers: headers } ).success(function() 

Setting HTTP Headers

The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

$httpProvider.defaults.headers.common (headers that are common for all requests): Accept: application/json, text/plain, * / *

$httpProvider.defaults.headers.post: (header defaults for POST requests) Content-Type: application/json

$httpProvider.defaults.headers.put (header defaults for PUT requests) Content-Type: application/json

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, eg `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.

The defaults can also be set at runtime via the $http.defaults object in the same fashion. In addition, you can supply a headers property in the config object passed when calling $http(config), which overrides the defaults without changing them globally.

For Authentication, I find this piece of code helpful. Assuming that the token is stored in cookie after successful login,

.factory('authInterceptor', function ($q, $cookieStore) {
    return {
        // Add authorization token to headers
        request: function (config) {
            config.headers = config.headers || {};
            if ($cookieStore.get('token')) {
                config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
            }
            return config;
        },

        // Intercept 401s and redirect you to login
        responseError: function(response) {
            if(response.status === 401) {
                // remove any stale tokens
                $cookieStore.remove('token');
                return $q.reject(response);
            }
            else {
                return $q.reject(response);
            }
        }
    };
})
.config(function ($httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM