繁体   English   中英

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

[英]How to enable CORS in an EmberJS application?

我有一个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');
});

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

import DS from 'ember-data';

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

应用程序/路由/ items.js

import Ember from 'ember';

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

应用程序/模型/ item.js

import DS from 'ember-data';

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

应用程序/模板/ 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上的服务器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM