Angular $http params encoding issue

2.8k views Asked by At

I have an Angular 1.4 service that makes an $http.get() request to the MapQuest API. If I pass my API key as part of the url directly then it works however if I add it as part of the params field then it does not.

Working:

var url = 'http://open.mapquestapi.com/geocoding/v1/address?key=Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4';

$http.get(url);

// Key actually sent
Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4

Not working:

var url = 'http://open.mapquestapi.com/geocoding/v1/address';

$http.get(url, { 
  params: { 
    key: 'Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4'
  }
});

// Key actually sent
 Gmjtd%257Cluub2d08nh%252C2s%253Do5-su2gh4

Not working either:

var url = 'http://open.mapquestapi.com/geocoding/v1/address';

$http.get(url, { 
  params: { 
    key: encodeURIComponent('Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4');
  }
});

// Key actually sent
Gmjtd%25257Cluub2d08nh%25252C2s%25253Do5-2u2gh4

It appears that passing the key in the params field causes it to undergo some kind of encoding process which renders it invalid.

How can I maintain the original key when using the params method?

1

There are 1 answers

0
Andy Gaskell On BEST ANSWER

Angular does indeed encode params. You should call decodeURIComponent since the key is already encoded.

$http.get(url, { 
  params: { 
    key: decodeURIComponent('Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4');
  }
});