mercredi 29 avril 2015

How to enable CORS in an EmberJS application?

I have an EmberJS application that uses ember-data to access data via a REST API. The REST API is running on the same machine but on a different port (although this probably applies to REST API's that are served from another domain.

When I go to the URL localhost:4200/items I get the following error in the Firefox console:

Content Security Policy: The page's settings blocked the loading of a resource at http://localhost:7654/api/items ("connect-src http://localhost:4200 ws://localhost:35729 ws://0.0.0.0:35729 http://0.0.0.0:4200").

I tried installing ember-cli-cors but nothing changed. I also tried the solution at http://ift.tt/1DWboNK, but that didn't work either. That discussion was from 2013, so that's not a huge surprise.

The REST API is written in python using Flask and Flask-cors. Using the network tab I can see that the request is being sent, and the data being sent back, but the error is still there.

app/router.js

import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

export default Router.map(function() {
  this.route('items');
});

app/adapters/application.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  namespace: 'api',
  host: 'http://localhost:7654',
});

app/routes/items.js

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return this.store.find('item');
  }
});

app/models/item.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr(),
});

app/templates/items.hbs

{{#each item in items}}
  {{ item.name }}<br>
{{else}}
  <p>No items</p>
{{/each}}

{{outlet}}




Aucun commentaire:

Enregistrer un commentaire