set backbone to point to an external endpoint

2019-08-26 21:44发布

问题:

In backbone, how can I point my entities to an external endpoint?

For example, my app is running on http://myapp.com

And I want it to use the followgin rest web service

http://external.com/api/rest/xxxx

I tried with urlRoot property but it doesn't seem to work that way

Sagan.FeatureModel = Backbone.Model.extend({
  defaults: {
    name: "New Feature",
    parent: "",
    enabled: false
  },
  urlRoot: 'http://localhost:9001/',
  url: 'features'
});

For testing purposes the app is hosted on localhost:9000, and the external webservice at localhost:9001.

backbone seems to still be pointing at localhost:9000 instead of 9001

回答1:

In your example you are setting customs urlRoot and url properties for the Model.

Setting up custom url property will make your custom urlRoot to be ignored due this property is used in the default url behavior, look on the Model.url documentation.

If you want your Model to use the endpoint http://external.com/api/rest/features just add it to the urlRoot and keep the url untouched:

urlRoot: "http://external.com/api/rest/features"

It will create routes like this:

GET http://external.com/api/rest/features/1

For fetching the Model with id 1.