访问从本地服务器的API [英] Access an API from local server

查看:228
本文介绍了访问从本地服务器的API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打电话给CTA API( http://www.transitchicago.com/developers /bustracker.aspx )从我的本地瓦帕服务器。但是,这样做的时候,通过骨干网收集取我得到:

  XMLHtt prequest无法加载http://www.ctabustracker.com/bustime/api/v1/getroutes?key=xx。没有访问控制 - 允许 - 原产地标头的请求的资源present。原产地'的http:// localhost'的,因此没有允许访问。
 

系列:

 定义([
模式/路由,
'核心'
],功能(路线){

返回Backbone.Collection.extend({

    初始化:功能(){},

    型号:路线,

    //网址:函数(){
    //回归http://www.ctabustracker.com/bustime/api/v1/getroutes?key=xx;
    //},

    网址:函数(){
        返回'/apiproxy.php?method=getroutes;
    },

 });

});
 

我知道这是一个常见的​​问题,但还没有找到一个简洁的答案。

我怎样才能解决这个问题? 更新 增加了apiproxy但我得到这个答复:

 远程地址:127.0.0.1:80
请求的URL:http://localhost/apiproxy.php方法= getroutes
请求方法:GET
状态code:200 OK
请求Headersview解析
GET /apiproxy.php?method=getroutes HTTP / 1.1
 

控制台:

 的responseText:$ URL =http://www.ctabustracker.com/bustime/api/v1/{$_GET['method']}?键= XX;
↵echo的file_get_contents($网址);

的SyntaxError {堆栈:(...)消息:意外令牌$}
消息:意外令牌$
堆栈:(...)
 

解决方案

您可以解决这个问题,但它不是一个简单的情况下,这一行添加到您的JavaScript和一切都会好起来。

您正在运行起来反对相同来源的安全政策内置到每一个网页浏览器。 起源基本上是指同一站点;我的JavaScript在example.com可以访问任何它喜欢在example.com,但它不能读取demonstration.com,example.net,或api.example.com任何东西。这是有不同的起源。 这里有什么才算是同根同源表。

如果没有它,我可以写一个网页,窃取所有的Gmail和私人facebook照片。我恶意的JavaScript将使得Web请求gmail.com和facebook.com,找到你的电子邮件和功放的联系;照片,加载的数据也是如此,然后把它送上自己的服务器。

显然,一些网页被设计为被其他人使用。的API,比如,一般要允许访问他们的数据,使人们可以构建Web应用程序。人们建立这些API可以为他们的内容与<一个href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#The_HTTP_response_headers"相对=nofollow> 访问控制 - 头告诉浏览器它的确定以允许从其他网站的请求。这就是所谓的CORS - 跨域资源共享。究其原因,你得到这个错误消息是因为ctabustracker.com开发商还没有添加任何CORS头。因此,你不能从你的JavaScript访问其API。


那么,有什么解决办法?你有两个选择:

  1. 通过电子邮件的ctabustracker.com管理员,并要求他们加入CORS头,允许从其他域访问。这是最对你的工作,但你的知识,基础设施,及放大器的摆布;及时对他们的开发团队。
  2. 在写自己的代理服务器。

同样的原产地政策只站在自己的方式在你的JavaScript。你可以做任何你喜欢的服务器上;在其最简单的,你可以创建一个 apiproxy.php 沿着这些路线:

  $ allExceptMethod = $ _GET; // PHP阵列复制按值
取消设置($ allExceptMethod ['法']);
$ URL =htt​​p://www.ctabustracker.com/bustime/api/v1/{$_GET['method']}?key=xx& 。 http_build_query($ allExceptMethod);
回声的file_get_contents($网址);
 

然后再从你的JavaScript访问它 /apiproxy.php?method=getroutes ,并通过标准的查询字符串传递额外的参数(例如, /apiproxy.php?method=test&foo=bar&cat=dog 导致请求 http://www.ctabustracker.com/bustime/api / V1 /测试键= XX和放大器;?富=酒吧和放大器;猫=狗)。现在,你的JavaScript正在请求自己的服务器,所以你不会有同样的原产地政策的任何问题。

您可以,当然,让你喜欢你的代理智能。它可以缓存响应,您的XML转换成JSON,pre取的结果很可能下一个请求,或可能对你的应用程序非常有用100其他的事情。

I am trying to call the CTA API (http://www.transitchicago.com/developers/bustracker.aspx) from my local Wamp server. 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:

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."

You're running up against the same-origin security policy built into every web browser. '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. 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. 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.

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. 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. This is called CORS - Cross-Origin Resource Sharing. The reason you get that error message is because the ctabustracker.com developers haven't added any CORS headers. Thus, you can't access their API from your JavaScript.


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. 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. You can do whatever you like on the server; at its simplest, you could create an apiproxy.php along these lines:

$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). Now your JavaScript is making a request to your own server, so you won't have any problems with the same-origin policy.

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.

这篇关于访问从本地服务器的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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