如何在 EmberJS 应用程序中启用 CORS? [英] How to enable CORS in an EmberJS application?
问题描述
我有一个 EmberJS 应用程序,它使用 ember-data 通过 REST API 访问数据.REST API 在同一台机器上运行,但在不同的端口上(尽管这可能适用于从另一个域提供服务的 REST API.
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.
当我转到 URL localhost:4200/items
时,我在 Firefox 控制台中收到以下错误:
When I go to the URL localhost:4200/items
I get the following error in the Firefox console:
内容安全策略:页面的设置阻止加载位于 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").
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 年开始的,所以这并不奇怪.
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.
REST API 是使用 Flask 和 Flask-cors 用 Python 编写的.使用网络选项卡我可以看到请求正在发送,数据正在发回,但错误仍然存在.正如预期的那样,响应中的标头 Access-Control-Allow-Origin
设置为 http://localhost:4200
.
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}}
推荐答案
这是 CSP 问题而非 CORS
This is a CSP issue not CORS
在 config/environment.js 中找到 ENV.contentSecurityPolicy 并将 http://localhost:7654 添加到您的连接"-src' 键
Inside config/environment.js find the ENV.contentSecurityPolicy and add http://localhost:7654 to your 'connect-src' key
例如
ENV.contentSecurityPolicy = {
// ... other stuff here
'connect-src': "'self' http://localhost:7654"
}
您可能还需要为您的生产环境进行不同的设置.
You will probably need a different setting for your production environment as well.
这篇关于如何在 EmberJS 应用程序中启用 CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!