1

There seems to be a lot of discussion on SO (e.g. these questions: A, B, C, D) and other sites (e.g the Ember docs) about configuring Ember to allow cross-origin requests. That's all fine and well, but I'd rather have Ember's back-end do the work of communicating with a remote service (Ember's server-side components to make the request, rather than the user's browser). Is this documented? Can someone provide an example?

Community
  • 1
  • 1
blong
  • 2,700
  • 6
  • 35
  • 97

1 Answers1

1

I thought I would find it easy to modify the HTTP server backing the ember serve command. Instead, I used the --proxy flag from Ember's CLI. It allows you to use remote services to provide data.

For this to work, let's assume a remote server foo.com:3000 provides JSON data at the path /resource. Configure a controller to GET the data like so:

import Ember from 'ember';

function getRemoteResource(store){
  var dfd = Ember.$.Deferred();

  Ember.$.ajax('/resource')
  .done(function(data){
    store.createRecord('model', data);
    dfd.resolve();
  })
  .fail(function(err){
    dfd.reject(new Error("An error occurred getting data.", err));
  });
  return dfd.promise();
}

export default Ember.Controller.extend({
  actions: {
    getResource:function(){
      var dataStore = this.store;
      return getRemoteResource(dataStore);
    }
  }
});

Use a template like this to invoke the controller's action:

<h2>Remote data example</h2>

<button class="my-button" {{action 'getResource' }}>
  Get resource
</button>

Assuming your code is on host bar.com, start ember like this : ember serve --proxy http://foo.com:3000. Then, open your browser to the appropriate page that loads the template (somewhere like http://bar.com:4200/index) , click the button and see that remote data is loaded.

blong
  • 2,700
  • 6
  • 35
  • 97