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

How to enable CORS in an EmberJS application?

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

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

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").

我尝试安装 ember-cli-cors 但没有任何改变。我也尝试了 http://discuss.emberjs.com/t/ember-data-and-cors/3690 的解决方案,但也没有用。该讨论是从 2013 年开始的,所以这不足为奇。

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

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}}

这是 CSP 问题而不是 CORS

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

例如

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

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

对于测试环境,您可以使用代理。

ember s -proxy http://localhost:7654

因此所有后端请求都会发送到您的服务器,该服务器位于端口 7654 上 运行。