Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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://discuss.emberjs.com/t/ember-data-and-cors/3690, 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. The header Access-Control-Allow-Origin is set to http://localhost:4200 in the response, as expected.

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}}
like image 980
Jon Avatar asked Apr 29 '15 14:04

Jon


2 Answers

This is a CSP issue not CORS

Inside config/environment.js find the ENV.contentSecurityPolicy and add http://localhost:7654 to your 'connect-src' key

e.g.

ENV.contentSecurityPolicy = {
  // ... other stuff here
  'connect-src': "'self' http://localhost:7654"
}

You will probably need a different setting for your production environment as well.

like image 107
David Duncan Avatar answered Nov 03 '22 11:11

David Duncan


For testing environment you can use proxy.

ember s -proxy http://localhost:7654

So all back-end request goes to your server which is running on port 7654.

like image 1
Balaji_V Avatar answered Nov 03 '22 10:11

Balaji_V