Rethabile February 2016

Angular Headers Web API

enter image description here

I am trying to add the X-APIKeys headers with every api call but they only have examples in curl. I have tried:

 var accessKey = "gdgfdgdfgdgdgfdgdfgfdgfdgdgh";
 var secretKey = "ggdgfdgdggtet565645654654654";
 $http.get("/information",{
  headers:{ {"X-APIKeys": accessKey, secretKey}}
    ) 

I have also tried to make an interceptor for config:

 config.headers['X-ApiKeys'] = {accessKey, secretKey}

The structure for X-APIKeys is what I think is causing me issues. I have provided a picture of the http headers they are looking for.

Full Request Header:

  Accept:*/*
  Accept-Encoding:gzip, deflate, sdch
  Accept-Language:en-US,en;q=0.8
  Access-Control-Request-Headers:accept, x-apikeys
  Access-Control-Request-Method:GET
  Connection:keep-alive
  Host:
  Origin:http://localhost:60531
  Referer:http://localhost:60531/
  User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36

Here is the request header from trying Tomislav example: enter image description here

Answers


Tomislav February 2016

Try this:

$http.get("/information",{
    headers: { 'X-ApiKeys': 'accessKey=' + accessKey+'; secretKey='+secretKey+';' }})


cristiano2lopes February 2016

You should do an interceptor, because there are probably some CORS negotiation going on (OPTIONS?). This guarantees that all the requests have the header. Of course if only the request to a certain host should have the header, you must have an if that decides the inclusion or not. The Config is just a service were you can keep the api key values. If you don't want to do it just hard code the values.

'use strict';

var app = angular.module('App');

app.factory('apiKeyInterceptor', [function (Config) {

    var header = 'accessKey=' + Config.accessKey+'; secretKey='+ Config.secretKey+';'
    return {
      request: function (config) {
        config.headers = config.headers || {};

        config.headers['X-ApiKeys'] = header;
        return config;
      }
    };
  }]);

var app = angular.module('App', []).config(function($httpProvider) {
    $httpProvider.interceptors.push('apiKeyInterceptor');
}

Also be careful and check if they mean the {} in the curl command literally or as a placeholder.

Post Status

Asked in February 2016
Viewed 1,802 times
Voted 7
Answered 2 times

Search




Leave an answer