Tadhg Tadhg - 1 year ago 118
AngularJS Question

Angularjs: Why does adding an authorization header cause a -1 status response?

I have a pre-existing angular code that gets data from an API. I'm trying to add an authentication token to the request.

To begin with I tried a simple example

.factory('getDep', [
'$resource', function($resource) {
return $resource('/ContactsDatabaseAPI/deps/:id', { id: '@id' }, {
query: {
method: 'GET',
isArray: false,
headers: {
'Authorization': 'Bearer ' + token
create: {
method: 'POST'
update: {
method: 'PUT'
remove: {
method: 'DELETE'

When the GET call is fired, and F12-ing in Chrome, I get an error message of:

angular.js:11821 OPTIONS http://localhost:56057/ContactsDatabaseAPI/deps net::ERR_CONNECTION_RESET

The return status of -1 and no sign of the call making it to the server side.

Without the headers line, it works fine.

If I try the GET call in Postman with the same Authorization value in the header, this also works fine.

I've also tried to add the header in the httpInterceptor and get the same result:

config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + authData.token;

Other things I've tried:

  • A random header name causes the same issue.

  • I've added 'Content-Type' = 'text/plain; charset=utf-8' as a header. This has no change to the result

I'm using angular 1.5.6

Answer Source

I've solved my issue and thanks to @Mourad-Idrissi for pointing me in the right direction.

The reason it worked before is that there was no Pre-Flight checks before the API was run. When I added the header, this changed the way the client communicated to the API. Now there was a OPTIONS call to the API which was causing the error. As the domain was different, this introduced me to the world of CORS.

By adding the following to my Application_BeginRequest() method in my backend Web API, Pre-flight now passes and my application continues.

if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download