简体   繁体   English

从本地服务器访问API

[英]Access an API from local server

I am trying to call the CTA API ( http://www.transitchicago.com/developers/bustracker.aspx ) from my local Wamp server. 我正在尝试从本地Wamp服务器调用CTA API( http://www.transitchicago.com/developers/bustracker.aspx )。 However, when doing the fetch via backbone collection I get: 但是,通过骨干收集进行提取时,我得到:

XMLHttpRequest cannot load http://www.ctabustracker.com/bustime/api/v1/getroutes?key=xx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

collection: 采集:

define([
'models/route',
'core'
], function (Route) {

return Backbone.Collection.extend({

    initialize: function () {},

    model: Route,

    //url: function () {
    //  return 'http://www.ctabustracker.com/bustime/api/v1/getroutes?key=xx';
    //},

    url: function () {
        return '/apiproxy.php?method=getroutes';
    },

 });

});

I know this is a common issue but haven't found a concise answer yet. 我知道这是一个常见问题,但尚未找到一个简明的答案。

How can I resolve this issue? 我该如何解决这个问题? Update Added the apiproxy but am getting this response: 更新添加了apiproxy,但正在收到此响应:

Remote Address:127.0.0.1:80
Request URL:http://localhost/apiproxy.php?method=getroutes
Request Method:GET
Status Code:200 OK
Request Headersview parsed
GET /apiproxy.php?method=getroutes HTTP/1.1

console: 安慰:

responseText: "$url = "http://www.ctabustracker.com/bustime/api/v1/{$_GET['method']}?   key=xx";
↵echo file_get_contents($url);

SyntaxError {stack: (...), message: "Unexpected token $"}
message: "Unexpected token $"
stack: (...)

You can solve this problem, but it's not a simple case of "add this line to your JavaScript and everything will be fine." 您可以解决此问题,但这不是“将这一行添加到JavaScript中,一切都会好的”的简单情况。

You're running up against the same-origin security policy built into every web browser. 您正在使用每个Web浏览器中内置的同源安全策略 'Origin' basically means 'the same site'; “来源”基本上是指“同一站点”; my JavaScript on example.com can access whatever it likes on example.com, but it's not allowed to read anything from demonstration.com, example.net, or api.example.com. 我在example.com上的JavaScript可以访问在example.com上喜欢的任何内容,但是不允许从demo.com,example.net或api.example.com读取任何内容。 That's got a different origin. 那有不同的起源。 Here's a table of what counts as the same origin . 这是一张算作同一原产地的表

Without it, I could write a web page that steals all your gmail and private Facebook photos. 没有它,我可能会写一个网页来窃取您所有的gmail和私人Facebook照片。 My malicious JavaScript would make web requests to gmail.com and facebook.com, find the links to your emails & photos, load that data too, and then send it off to my own server. 我的恶意JavaScript会向gmail.com和facebook.com发出Web请求,找到指向您的电子邮件和照片的链接,也加载该数据,然后将其发送到我自己的服务器上。

Obviously, some web pages are designed to be used by other people. 显然,某些网页被设计为供其他人使用。 APIs, for instance, generally want to allow access to their data so people can build web apps. 例如,API通常希望允许访问其数据,以便人们可以构建Web应用程序。 The people building those APIs can serve their content with Access-Control- headers that tell browsers it's OK to allow requests from other sites. 构建这些API的人员可以使用Access-Control-标头提供其内容,该标头告诉浏览器可以接受来自其他站点的请求。 This is called CORS - Cross-Origin Resource Sharing. 这称为CORS-跨域资源共享。 The reason you get that error message is because the ctabustracker.com developers haven't added any CORS headers. 您收到该错误消息的原因是因为ctabustracker.com开发人员未添加任何CORS标头。 Thus, you can't access their API from your JavaScript. 因此,您无法从JavaScript访问其API。


So what's the solution? 那么解决方案是什么? you have two options: 您有两种选择:

  1. Email the ctabustracker.com admins and ask them to add CORS headers to allow access from other domains. 给ctabustracker.com管理员发送电子邮件,并要求他们添加CORS标头以允许来自其他域的访问。 This is the least work for you, but you're at the mercy of the knowledge, infrastructure, & promptness of their development team. 这是最不适合您的工作,但是您受其开发团队的知识,基础架构和及时性的支配。
  2. Write your own proxy server. 编写自己的代理服务器。

The same-origin policy is only standing in your way in your JavaScript. 同源策略仅会妨碍您使用JavaScript。 You can do whatever you like on the server; 您可以在服务器上做任何您想做的事; at its simplest, you could create an apiproxy.php along these lines: 最简单的说,您可以按照以下方式创建apiproxy.php

$allExceptMethod = $_GET; // PHP arrays are copy-by-value
unset($allExceptMethod['method']);
$url = "http://www.ctabustracker.com/bustime/api/v1/{$_GET['method']}?key=xx&" . http_build_query($allExceptMethod);
echo file_get_contents($url);

And then access it from your JavaScript as /apiproxy.php?method=getroutes , and pass extra parameters in via a standard query string (for instance, /apiproxy.php?method=test&foo=bar&cat=dog results in a request to http://www.ctabustracker.com/bustime/api/v1/test?key=xx&foo=bar&cat=dog ). 然后从您的JavaScript中以/apiproxy.php?method=getroutes对其进行访问,并通过标准查询字符串传入其他参数(例如,/ /apiproxy.php?method=test&foo=bar&cat=dog导致对http://www.ctabustracker.com/bustime/api/v1/test?key=xx&foo=bar&cat=dog的请求http://www.ctabustracker.com/bustime/api/v1/test?key=xx&foo=bar&cat=dog )。 Now your JavaScript is making a request to your own server, so you won't have any problems with the same-origin policy. 现在,您的JavaScript向您自己的服务器发出请求,因此同源策略不会有任何问题。

You can, of course, make your proxy as smart as you like. 当然,您可以根据需要使代理变得聪明。 It could cache responses, convert your XML to JSON, pre-fetch the results for likely next requests, or 100 other things that may be useful for your app. 它可以缓存响应,将XM​​L转换为JSON,为可能的下一个请求预取结果,或对您的应用有用的100件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM