Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

jquery - backbone.js and cross domain scripting

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/'
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...