如何在EmberJS应用程序中启用CORS?

Jon*_*Jon 12 rest cors ember.js

我有一个EmberJS应用程序,它使用ember-data通过REST API访问数据.REST API在同一台机器上运行,但在不同的端口上运行(尽管这可能适用于从另一个域提供的REST API.

当我转到URL时,localhost:4200/items我在Firefox控制台中收到以下错误:

内容安全策略:页面的设置阻止了在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 ").

我试过安装ember-cli-cors但没有改变.我也在http://discuss.emberjs.com/t/ember-data-and-cors/3690尝试了解决方案,但这也没有用.那次讨论是从2013年开始的,所以这不是一个巨大的惊喜.

REST API是使用Flask和Flask-cors在python中编写的.使用网络选项卡,我可以看到正在发送请求,并且数据被发回,但错误仍然存​​在.正如预期的那样,标头在响应中Access-Control-Allow-Origin设置http://localhost:4200为.

应用程序/ 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');
});
Run Code Online (Sandbox Code Playgroud)

应用程序/适配器/ application.js中

import DS from 'ember-data';

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

应用程序/路由/ items.js

import Ember from 'ember';

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

应用程序/模型/ item.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr(),
});
Run Code Online (Sandbox Code Playgroud)

应用程序/模板/ items.hbs

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

{{outlet}}
Run Code Online (Sandbox Code Playgroud)

Dav*_*can 9

这是CSP问题而不是CORS

在config/environment.js中找到ENV.contentSecurityPolicy并将http:// localhost:7654添加到'connect-src'键

例如

ENV.contentSecurityPolicy = {
  // ... other stuff here
  'connect-src': "'self' http://localhost:7654"
}
Run Code Online (Sandbox Code Playgroud)

您可能还需要为生产环境设置不同的设置.

  • 这是使用 CSP https://github.com/rwjblue/ember-cli-content-security-policy 的 ember 插件 (2认同)