作为Ember.js的初学者,我尝试从Rails Api服务器获取一些数据到Ember App。我的Ember App试图获取并显示rails api提供的类别名称。 我正在使用
应用程序/ router.js
PowerMockito.spy(Notification.class);
PowerMockito.suppress(PowerMockito.method(Notification.class, "setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class));
路由/类别/ index.js
Router.map(function() {
this.resource('categories',function(){
this.resource('category',{path: '/:category_id'});
});
});
应用程序/模型/ category.js
export default Ember.Route.extend({
model() {
return this.store.findAll('category')
}
});
应用程序/适配器/ application.js中
export default DS.Model.extend({
name: DS.attr('string')
});
应用程序/模板/类别/ index.hbs
export default DS.JSONAPIAdapter.extend({
shouldReloadAll: function() { return true; },
namespace: 'v1',
host: 'http://ip.address-to_rails_api'
});
现在,当我在浏览器中访问http://ip.address-to_rails_api时,我得到了回复
<ul>
{{#each model as |category|}}
<li>{{category.name}}</li>
{{/each}}
</ul>
但是当我在我的余烬应用中访问/分类时,http://localhost:4200/categories 注释显示在浏览器中,我在ember检查器中出错
{"categories":[{"id":1,"name":"Entertainment"}, {"id":2,"name":"Education"}]}
另外,ember服务器控制台反映错误
routeName: "categories.index_error"
context: Error: Adapter operation failed
currentModel: Error: Adapter operation failed
我也尝试将JSONAPIAdapter更改为RESTAdapter,但它给出了弃用错误。请帮我理解这个问题。
答案 0 :(得分:4)
终于解决了这个问题 问题出在Rails API和Ember App两个部分
上第一次错误
Content Security Policy violation: {}
通过向ember app添加内容安全策略来删除配置/ environment.js
contentSecurityPolicy: {
'default-src': "'none'",
'font-src': "'self'",
'img-src': "'self'",
'media-src': "'self'",
'style-src': "'self' 'unsafe-inline'",
'script-src': "'self' 'unsafe-eval' http://ip_to_rails_api",
'connect-src': "'self' ws://ip_to_rails_api"
}
然后我收到了错误
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.
通过在rails api端使用跨源资源共享或CORS解决了此错误。因此,对于每个请求,浏览器首先发送OPTIONS请求,然后服务器返回带有一些额外标头的响应。然后,浏览器可以发出原始请求。
有关CORS的更多信息,请参阅How does Access-Control-Allow-Origin header work?