Backbone.js的和跨域脚本 [英] backbone.js and cross domain scripting

查看:363
本文介绍了Backbone.js的和跨域脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与Backbone.js的和jQuery工作。该应用程序应该在手机上离线状态下运行(即本地主机),也有在互联网某处服务器端后端几个电话。

什么是实现与Backbone.js的跨域请求的最佳方式?

我想用JSON,但如果需要,我可以最终切换回去休息。

下面是我不是很IM pressive code迄今:

  App.Collections.Events = Backbone.Collection.extend({
   型号:事件,
   网址:'http://mydomain.com/api/getevents/user_id/1/
});


解决方案

有允许跨域XMLHtt prequests,这是Backbone.js的使用从URL获取数据的方法有两种方式。首先是适当的,如果你有你想连接到非原始域的服务器端的控制,并涉及implenting的跨来源资源共享(或CORS)。

要实现CORS,返回原点部分HTTP 引用站点请求头(位到路径的开头;它应该与正则表达式 ^ + \\ / {2} [^ \\ /] * 接入控制 - >)。?允许来源响应头为要有助于域:

 访问控制允许来源:http://mydomain.com

您可能需要重写 Backbone.sync 为了使的右键设置要在XMLHtt prequest对象上设置。

第二个选项,如果你没有进入到交叉源服务器,将代理通过自己的服务器(无论是起源一对一或使CORS)的请求。显然,谁拥有你想打电话可能不喜欢你这样做的领域,但是这是由设计 - 如果他们不希望你叫你的服务做,他们只拥有,而不是每一个IP地址来阻止,你客户端的IP。

I want to work with backbone.js and jquery. The app is supposed to run offline on mobile phones (i.e. "localhost"), there are few calls on a server side backend somewhere in the internet.

What is the best way to realize cross domain requests with backbone.js?

I would like to use JSON, but I could eventually switch back to REST if necessary.

Here's my not very impressive code so far:

App.Collections.Events = Backbone.Collection.extend({
   model: Event,    
   url: 'http://mydomain.com/api/getevents/user_id/1/'
});

解决方案

There are two ways of allowing cross-domain XMLHttpRequests, which is the method Backbone.js uses to fetch data from a URL. The first is appropriate if you've got control of the server-side of the non-origin domain you're trying to connect to, and involves implenting Cross-Origin Resource Sharing (or CORS).

To implement CORS, return the 'Origin' part the HTTP Referer request header (the bit up to the beginning of the path; it should match regex ^.+?\/{2}[^\/]*) in the Access-Control-Allow-Origin response header for domains you want to serve to:

 Access-Control-Allow-Origin: http://mydomain.com

You might need to override Backbone.sync in order for the right settings to be set on the XMLHttpRequest object.

The second option, if you don't have access to the cross-origin server, would be to proxy the requests through your own server (either the origin one or one which enables CORS). Obviously whoever owns the domain you're trying to call mightn't like you doing that, but that is by design - if they don't want you calling your service, they only have one IP address to block, instead of each of your clients' IP.

这篇关于Backbone.js的和跨域脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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