配置Ember的后端与RESTful服务进行通信 [英] Configure Ember's back-end to communicate with a RESTful service
问题描述
似乎有很多关于SO的讨论(例如这些问题: A , B , C , D )和其他网站(例如 Ember docs )关于配置Ember以允许跨原始请求。这很好,但我宁愿让Ember的后端做远程服务的通信工作(Ember的服务器端组件来发出请求,而不是用户的浏览器)。这是否记录在案?有人可以提供一个例子吗?
There seems to be a lot of discussion on SO (e.g. these questions: A, B, C, D) and other sites (e.g the Ember docs) about configuring Ember to allow cross-origin requests. That's all fine and well, but I'd rather have Ember's back-end do the work of communicating with a remote service (Ember's server-side components to make the request, rather than the user's browser). Is this documented? Can someone provide an example?
推荐答案
我以为我会很容易修改支持 ember serve
命令。相反,我使用Ember的CLI中的 - proxy
标志。它允许您使用远程服务来提供数据。
I thought I would find it easy to modify the HTTP server backing the ember serve
command. Instead, I used the --proxy
flag from Ember's CLI. It allows you to use remote services to provide data.
为此,让我们假设远程服务器 foo.com:3000
在路径 / resource
提供JSON数据。配置控制器以获取数据,如下所示:
For this to work, let's assume a remote server foo.com:3000
provides JSON data at the path /resource
. Configure a controller to GET the data like so:
import Ember from 'ember';
function getRemoteResource(store){
var dfd = Ember.$.Deferred();
Ember.$.ajax('/resource')
.done(function(data){
store.createRecord('model', data);
dfd.resolve();
})
.fail(function(err){
dfd.reject(new Error("An error occurred getting data.", err));
});
return dfd.promise();
}
export default Ember.Controller.extend({
actions: {
getResource:function(){
var dataStore = this.store;
return getRemoteResource(dataStore);
}
}
});
使用这样的模板调用控制器的操作:
Use a template like this to invoke the controller's action:
<h2>Remote data example</h2>
<button class="my-button" {{action 'getResource' }}>
Get resource
</button>
假设您的代码位于主机上 bar.com
,启动ember这样: ember serve --proxy http://foo.com:3000
。然后,将浏览器打开到加载模板的相应页面(像 http://bar.com:4200/index
),点击按钮,看到远程数据已加载。
Assuming your code is on host bar.com
, start ember like this : ember serve --proxy http://foo.com:3000
. Then, open your browser to the appropriate page that loads the template (somewhere like http://bar.com:4200/index
) , click the button and see that remote data is loaded.
这篇关于配置Ember的后端与RESTful服务进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!