$http Auth Headers in AngularJS

前端 未结 8 749
闹比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: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!

提交回复
热议问题