0

我有一个 REST 服务http://restservice.net。我正在骨干网中实现此服务的客户端。客户端只是一个 html 文件(用于引导应用程序)和一堆 js 文件,其中包含我的backbonejs 代码。我将这些文件托管在另一个站点上http://client.net

我的backbonejs代码正在调用,http://restservice.net但由于same origin policy. 我已经看过其他关于我如何只能交谈的 SO 问题http://client.net

我是否必须通过http://client.net. 我认为这是低效的。那么使用客户端 MVC 框架有什么意义呢?我在这里错过了什么吗?

4

1 回答 1

5

You have two options: JSONP and CORS both of these demand that your http://restservice.net server is setup to suppor the protocols. Forcing backbone to use JSONP simply requires you passing an option to Backbone.sync. One way to do this is like this:

sync: function(method, model, options){   
   options.dataType = "jsonp";  
   return Backbone.sync(method, model, options);  
}  

The problem with JSONP is that you can only make GET requests, so your REST api is effectively read only. To get CORS working you simply need to configure your api server to send back the proper headers . This would pretty liberal:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, PUT, DELETE OPTIONS  

here is a pretty good run down on CORS. If you set that up, then things will pretty much work as usual.

If you don't have the ability to make changes to the server at http://restservice.net then you have no choice but to proxy all the requests to that service. This is definately inefficient but implementing is probably simpler than you would expect. One thing to consider is a reverse proxy

于 2012-05-03T06:52:52.123 回答