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

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

问题描述

我想使用backbone.js 和jquery.该应用程序应该在手机(即本地主机")上离线运行,在互联网某处的服务器端后端几乎没有调用.

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.

使用backbone.js 实现跨域请求的最佳方式是什么?

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

我想使用 JSON,但如果有必要,我最终可以切换回 REST.

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

推荐答案

允许跨域 XMLHttpRequests 有两种方式,这是 Backbone.js 从 URL 获取数据的方法.如果您已经控制了您尝试连接的非源域的服务器端,并且涉及实施 跨源资源共享(或 CORS).

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

要实现 CORS,返回 HTTP Referer 请求标头的Origin"部分(path 开头的位;它应该匹配正则表达式 ^.+?/{2}[^/]*) 在 Access-Control-Allow-Origin 响应标头中您要服务的域:

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

您可能需要覆盖 Backbone.sync 以便 正确设置要在 XMLHttpRequest 对象上设置.

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

如果您无权访问跨源服务器,则第二种选择是通过您自己的服务器(源服务器或启用 CORS 的服务器)代理请求.显然,拥有您尝试呼叫的域的人可能不喜欢您这样做,但这是设计使然 - 如果他们不想让您呼叫您的服务,他们只有一个 IP 地址要阻止,而不是您的每个 IP 地址客户的IP.

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天全站免登陆