Adding a custom header to an HTTP request using angular.js

I am new to angular.js and I am trying to add some headers to the request:

var config = {headers: { 'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==', 'Accept': 'application/json;odata=verbose' } }; $http.get('https://www.example.com/ApplicationData.svc/Malls(1)/Retailers', config).success(successCallback).error(errorCallback); 

I looked through all the documentation and it seems to me that this should be correct.

When I use the local file for the URL in $http.get , I see the following HTTP request on the network tab in Chrome:

 GET /app/data/offers.json HTTP/1.1 Host: www.example.com Connection: keep-alive Cache-Control: max-age=0 If-None-Match: "0f0abc9026855b5938797878a03e6889" Authorization: Basic Y2hhZHN0b25lbWFuOkNoYW5nZV9tZQ== Accept: application/json;odata=verbose X-Requested-With: XMLHttpRequest If-Modified-Since: Sun, 24 Mar 2013 15:58:55 GMT User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22 X-Testing: Testing Referer: http://www.example.com/app/index.html Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 

As you can see, both headers have been added correctly. But when I change the URL to the one shown in $http.get above (except for using a real address, not example.com), I get:

 OPTIONS /ApplicationData.svc/Malls(1) HTTP/1.1 Host: www.datahost.net Connection: keep-alive Access-Control-Request-Method: GET Origin: http://mpon.site44.com User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22 Access-Control-Request-Headers: accept, origin, x-requested-with, authorization, x-testing Accept: */* Referer: http://mpon.site44.com/app/index.html Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 

The only difference between the two code is that for the first URL is a local file, and for the second URL is a remote server. If you look at the second request header, there is no authentication header, and Accept seems to use the default value instead. In addition, the first line now says OPTIONS instead of GET (although the Access-Control-Request-Method is GET ).

Any idea what is wrong with the code above, or how to get additional headers included in use when not using a local file as a data source?

+83
javascript angularjs
Mar 24 '13 at 13:16
source share
8 answers

I took what you had and added another X-Testing header

 var config = {headers: { 'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==', 'Accept': 'application/json;odata=verbose', "X-Testing" : "testing" } }; $http.get("/test", config); 

And on the Chrome network tab, I see that they are being sent.

 GET /test HTTP/1.1 Host: localhost:3000 Connection: keep-alive Accept: application/json;odata=verbose X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22 Authorization: Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ== X-Testing: testing Referer: http://localhost:3000/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 

You do not see them in the browser or on the server? Try using a browser tool or debugging proxy and see what is being sent.

+60
Mar 24 '13 at 14:16
source

Basic authentication using the HTTP POST method:

 $http({ method: 'POST', url: '/API/authenticate', data: 'username=' + username + '&password=' + password + '&email=' + email, headers: { "Content-Type": "application/x-www-form-urlencoded", "X-Login-Ajax-call": 'true' } }).then(function(response) { if (response.data == 'ok') { // success } else { // failed } }); 

... and a call to the GET method with the header:

 $http({ method: 'GET', url: '/books', headers: { 'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==', 'Accept': 'application/json', "X-Login-Ajax-call": 'true' } }).then(function(response) { if (response.data == 'ok') { // success } else { // failed } }); 
+16
Jan 01 '15 at 16:45
source

my suggestion will be to add function call settings like this inside the function check the header that suits it. I am sure this will definitely work. It works great for me.

 function getSettings(requestData) { return { url: requestData.url, dataType: requestData.dataType || "json", data: requestData.data || {}, headers: requestData.headers || { "accept": "application/json; charset=utf-8", 'Authorization': 'Bearer ' + requestData.token }, async: requestData.async || "false", cache: requestData.cache || "false", success: requestData.success || {}, error: requestData.error || {}, complete: requestData.complete || {}, fail: requestData.fail || {} }; } 

then call your data as follows

  var requestData = { url: 'API end point', data: Your Request Data, token: Your Token }; var settings = getSettings(requestData); settings.method = "POST"; //("Your request type") return $http(settings); 
+7
Jan 07 '15 at 11:11
source

If you want to add your own headers to ALL requests, you can change the default values โ€‹โ€‹to $ httpProvider to always add this header ...

 app.config(['$httpProvider', function ($httpProvider) { $httpProvider.defaults.headers.common = { 'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==', 'Accept': 'application/json;odata=verbose' }; }]); 
+7
Nov 21 '15 at 8:04
source

What you see for the OPTIONS request is fine. Authorization headers do not appear in it.

But for basic auth to work, you need to add: withCredentials = true; to your var config .

From an AngularJS $ http document:

withCredentials - {boolean} - set the withCredentials flag of an XHR object. For more information, see credential requests information.

+2
Mar 24 '13 at 16:58
source

And what is the answer from the server? It should answer 204, and then really send the GET request you request.

In OPTIONS, the client checks to see if the server allows a CORS request. If it gives you something other than 204, then you must configure the server to send the correct Allow-Origin headers.

The way to add headers is the right way to do this.

+1
Jun 24 '13 at 19:10
source

Chrome is preceded by a search request for CORS headers. If the request is acceptable, it will send a real request. If you are running this cross-domain, you just have to deal with it or find a way to make the request non-cross-domain. This is by design.

Unlike simple requests (see above), the โ€œprefilledโ€ requests are first requested; send an HTTP request using the OPTIONS method to a resource in another domain to determine if the actual request is safe to send. Cross-site request requests are preceded in this way, as they may have implications for user data. In particular, a request is preceded if:

It uses methods other than GET, HEAD, or POST. Also, if POST is used to send request data using Content-Type, other than application / x-www-form-urlencoded, multipart / form-data or text / plain, for example if the POST request sends an XML payload to the server using application / xml or text / xml, then the request is preceded. It sets custom headers in the request (for example, the request uses a header such as X-PINGOTHER)

Link: AJAX in Chrome sends OPTIONS instead of GET / POST / PUT / DELETE?

+1
Feb 08 '16 at 12:52 on
source

The following explanatory fragment worked for me. Maybe you shouldn't use ' for the title name?

 { headers: { Authorization: "Basic " + getAuthDigest(), Accept: "text/plain" } } 

I use $http.ajax() , although I would not expect this to be a game change.

-8
Mar 24 '13 at 13:42
source



All Articles