Himanshu Soni
Himanshu Soni

Reputation: 364

Backbone.js With RestAPI

I am a noob to javascript and specially Backbone.js I am following this tutorial and tweaked the models and urls to my own Rest Services(JaxRS). However, on running the app in browser (Chrome) gives me the following error XMLHttpRequest cannot load http://localhost:1232/abc. Origin null is not allowed by Access-Control-Allow-Origin

On searching for some solutions over this error,

  1. i read on a post on SO to start the chrome with the parameters --allow-file-access-from-files – However, i am not sure about this method. And neither i could try this due to some reasons.
  2. Also i read that in plain javascript, such kind of issues are usually handled using an xmlDomainObject. But this is not a case with backbone.

So what i am looking for, is some method by which i can solve the issue through backbone itself. Also i dont understand, why this kind of issue was not addressed in any of the tutorials on using backbone with RestApi

Upvotes: 2

Views: 602

Answers (2)

codemonkey
codemonkey

Reputation: 5267

This has nothing to do with Backbone specifically. You are loading the page with a file:/// URL and the problem is an AJAX Cross Origin request.

There are ways around it - you could load your web pages through your server which is running the REST services. Alternatively, you could allow cross origin requests. I'll let you search for how to do that.

EDIT If you are developing a PhoneGap application, you will not have the issue once you actually run the application since it will not complain about cross origin requests. At that point it is a local app so the request is not cross-origin. The way to get around that at development time is the --allow-file-access flag which you said you could not get to work. You need to make sure to close any other open Chrome windows and then start a new instance with that flag.

Upvotes: 2

Mandeep Jain
Mandeep Jain

Reputation: 2664

You can use JSONP in your ajax call which allows cross origin requests

Read more at here and here

EDIT :

Using jsonp expects back a json object, and it does not work with xml. So mayb you need to wrap your XML into json before sending from the server, or parse your xml to json.

this, this and this may prove helpful :)

Upvotes: 1

Related Questions