AngularJS and an external API - getting it to work

2019-06-24 02:06发布

问题:

I've been trying to access the sqwiggle API inside my Angular app and was testing it using Postman. All seems to work fine. I define a Basic Auth header, do a GET request to the messages endpoint and I get a nice response. These are the request headers (from Postman):

Request URL:https://api.sqwiggle.com/messages
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,nl;q=0.6
Authorization:Basic [secret]
Cache-Control:no-cache
Connection:keep-alive
Host:api.sqwiggle.com
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.70 Safari/537.36

Now in my AngularJS app, I want to do the same:

$http.get('https://api.sqwiggle.com/messages', {
    headers: {
        Authorization: 'Basic [secret]'
    }
}).success(function(e) {
    alert(e);
});

But this results in the following request headers:

Request URL:https://api.sqwiggle.com/messages
Request Method:OPTIONS
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,nl;q=0.6
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:api.sqwiggle.com
Origin:http://localhost:8888
Referer:http://localhost:8888/
User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53

Given the fact that Postman uses JS to get the data from the API, it should be possible in AngularJS too, or am I missing something here? Why is Angular transforming the GET in an OPTIONS request and why is it not adding the Authorization header?

Thanks for your help

回答1:

Try something like this instead of using $http.get

$http({
    method: "get",
    url: "https://api.sqwiggle.com/messages",
    headers: {
        'Authorization' : 'Basic secret'
    }
}).success(function(data) {
    console.log(data);
});