Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js and cross domain scripting

Tags:

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/'
});
like image 815
herrjeh42 Avatar asked Jun 26 '11 19:06

herrjeh42


People also ask

What is backbone JS used for?

BackboneJS is a lightweight JavaScript library that allows to develop and structure the client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.

Is backbone a JavaScript framework?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Is Backbone JS open source?

Backbone is an open-source component of DocumentCloud.


1 Answers

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.

like image 99
Stoive Avatar answered Oct 06 '22 00:10

Stoive