【问题标题】:How to enable CORS in an EmberJS application?如何在 EmberJS 应用程序中启用 CORS?
【发布时间】:2015-07-08 22:32:15
【问题描述】:

我有一个 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

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

【问题讨论】:

标签: rest ember.js cors


【解决方案1】:

这是 CSP 问题,而不是 CORS

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

例如

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

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

【讨论】:

【解决方案2】:

测试环境可以使用代理。

ember s -proxy http://localhost:7654

所以所有后端请求都会发送到您在端口 7654 上运行的服务器。

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 2013-02-03
    • 2015-07-24
    • 2023-01-13
    • 1970-01-01
    • 2017-01-21
    • 2018-10-15
    • 2021-12-08
    • 2015-09-24
    相关资源
    最近更新 更多