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

Adding a custom header to HTTP request using angular.js


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 in the Chrome network tab, I see them being sent.

GET /test HTTP/1.1Host: localhost:3000Connection: keep-aliveAccept: application/json;odata=verboseX-Requested-With: XMLHttpRequestUser-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.22Authorization: Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==X-Testing: testingReferer: http://localhost:3000/Accept-Encoding: gzip,deflate,sdchAccept-Language: en-US,en;q=0.8Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Are you not seeing them from the browser, or on the server? Try the browser tooling or a debug proxy and see what is being sent out.


Basic authentication using 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 GET method call with 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    }});


If you want to add your custom headers to ALL requests, you can change the defaults on $httpProvider to always add this header…

app.config(['$httpProvider', function ($httpProvider) {    $httpProvider.defaults.headers.common = {         'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',        'Accept': 'application/json;odata=verbose'      };}]);