How to enable CORS in an EmberJS application?

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

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.

When I go to the URL localhost:4200/items I get the following error in the Firefox console:

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

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.

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

No items

{{/each}} {{outlet}}

回答1:

This is a CSP issue not CORS

Inside config/environment.js find the ENV.contentSecurityPolicy and add http://localhost:7654 to your 'connect-src' key

e.g.

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

You will probably need a different setting for your production environment as well.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!