AngularJS和外部API - 得到它像邮递员工作 [英] AngularJS and an external API - getting it to work like PostMan

查看:166
本文介绍了AngularJS和外部API - 得到它像邮递员工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图进入我的角度应用程序内的sqwiggle API并使用测试它的邮差。一切似乎很好地工作。我定义了一个基本认证头,做一个GET请求到端点的消息,我得到一个不错的回应。这些都是请求头(从邮差):

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

现在在我的应用程序AngularJS,我想这样做是相同的:

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

由于邮递员使用JS从API获取数据的事实,应该在AngularJS可能也一样,还是我失去了一些东西?为什么角改变在OPTIONS请求GET和为什么它不添加授权头?

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?

感谢您的帮助。

推荐答案

尝试这样的事情,而不是使用 $ http.get

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);
});

这篇关于AngularJS和外部API - 得到它像邮递员工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆