$http Auth Headers in AngularJS

前端 未结 8 705
闹比i
闹比i 2020-11-30 21:52

I have an angular application that is hitting a node API. Our backend developer has implemented basic auth on the API, and I need to send an auth header in my request.

相关标签:
8条回答
  • 2020-11-30 22:21

    Try base64 encoding your user:password before you append it to "Basic", as in:

    headers: {
      'Authorization': "Basic " + auth64EncodedUserColonPass
    }
    
    0 讨论(0)
  • 2020-11-30 22:23

    You can use it in the controller:

    .controller('Controller Name', ['$http', function($http) {
       $http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password;
    }]);
    
    0 讨论(0)
  • 2020-11-30 22:24

    You're mixing the use cases; instantiated services ($http) cannot be used in the config phase, while providers won't work in run blocks. From the module docs:

    • Configuration blocks - […] Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
    • Run blocks - […] Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

    So use either of the following:

    app.run(['$http', function($http) {
        $http.defaults.headers.common['Authorization'] = /* ... */;
    }]);
    
    app.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.headers.common['Authorization'] = /* ... */;
    }])
    
    0 讨论(0)
  • 2020-11-30 22:24

    add below line in your aap.run method

    $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
    
    0 讨论(0)
  • 2020-11-30 22:28

    In the angularjs documentation you can see some ways to set headers but I think this is what you are searching:

    $http({
        method: 'POST',
        url: '/theUrl',
        headers: {
            'Authorization': 'Bearer ' + 'token'
             //or
             //'Authorization': 'Basic ' + 'token'
        },
        data: someData
    }).then(function successCallback(response) {
        $log.log("OK")
    }, function errorCallback(response) {
        if(response.status = 401){ // If you have set 401
            $log.log("ohohoh")
        }
    });
    

    I'm using this structure in my angularjs client with an ASP.NET 5 server and it works.

    0 讨论(0)
  • 2020-11-30 22:36

    WORKING EXAMPLE: I have learnt this from @MrZime - Thanks! and Read https://docs.angularjs.org/api/ng/service/$http#setting-http-headers

    Latest v1.6.x of NGULARJS as of 2018 MARCH 2nd

            var req = {
                method: 'POST',
                url: 'https://api.losant.com/applications/43fdsf5dfa5fcfe832ree/data/last-value-query',
                headers: {
                    'Authorization': 'Bearer ' + 'adsadsdsdYXBpVG9rZW4iLCJzrdfiaWF0IjoxNdfsereOiJZ2V0c3RfdLmlvInfdfeweweFQI-dfdffwewdf34ee0',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                data: {
                    "deviceIds": [
                        "a6fdgdfd5dfqaadsdd5",
                        "azcxd7d0ghghghghd832"
                    ],
                    "attribute": "humidity"
                }
            }
    
    
    
    
            $http(req).then(function successCallback(response) {
    
                $log.log("OK!")
                 returnedData = response.data
    
            }, function errorCallback(response) {
    
                if (response.status = 401) { // If you have set 401
    
                    $log.log("BAD 401")
    
                }
                else {
    
                    $log.log("broken at last")
    
                }
            });
    

    Add it to your.js file and include this your.js in your.html file and look at console panel in debug/F12 on chrome you should get OK status and "returnedData" is what you want in the end. Enjoy the data!

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