Backbonejs - CORS错误 [英] Backbonejs - CORS error

查看:130
本文介绍了Backbonejs - CORS错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个REST服务坐在 http://restservice.net 。我采取一个客户在骨干这项服务。客户端是一个简单的HTML文件(自举程序)的握着我的backbonejs code js文件和一堆。我托管在其他网站 http://client.net 这些文件。

I have a REST service sitting at http://restservice.net. I am implementing a client for this service in backbone. The client is simply an html file (for bootstrapping the application) and bunch of js files holding my backbonejs code. I am hosting these files on another site http://client.net.

我backbonejs code被调用到 http://restservice.net ,但现在由于允许同源策略。我已经看着那个说说我怎么能只跟 http://client.net 其他等问题。

My backbonejs code is calling into http://restservice.net but now allowed due to same origin policy. I have already looked at other SO questions that talk about how I can only talk to http://client.net.

我一定要通过重定向 http://client.net 每一个要求。我认为这是低效率的。什么是在使用客户端MVC框架那么点?我失去了一些东西在这里?

Do I have to redirect every request through http://client.net. I see that as inefficient. What's the point in using a client side MVC framework then? Am I missing something here?

推荐答案

您有两种选择:JSONP和CORS这两种需求,你的 http://restservice.net 服务器所suppor的协议。强制骨干使用JSONP只需要你传递一个选项, Backbone.sync 。这样做的一个办法是这样的:

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);  
}  

与JSONP的问题是,你只能让GET请求,所以你的REST API有效地只读。为了让CORS工作,你只需要简单地配置您的API服务器发送回正确的头。这将pretty自由主义:

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  

是pretty良好的运行下来上CORS。如果设置了,那么事情将pretty很多工作照常进行。

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

如果你没有在 http://restservice.net 来更改服务器的能力,那么你就别无选择,只能代理的所有请求该服务。这肯定是低效率的,但实现比你所期望的可能更简单。有一点要考虑的是一个反向代理

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

这篇关于Backbonejs - CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆