Rails ajax Cross Domain Requests 问题

略晓技术大牛!急!我有一个jQuery的$.post请求跨域了,Chrome提示:

XMLHttpRequest cannot load http://External-IP:port/posts. Origin http://myTestdomain.tld is not allowed by Access-Control-Allow-Origin.

折腾我一晚上了,到底怎样才能让Rails接受这个请求呢?描述详细点,5块钱就给你了!疯了我

1 个回答

首先,把下面代码加到application_controller.rb里:

before_filter :cor
def cor
  headers["Access-Control-Allow-Origin"]  = "js-app-origin.com"
  headers["Access-Control-Allow-Methods"] = %w{GET POST PUT DELETE}.join(",")
  headers["Access-Control-Allow-Headers"] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(",")
  head(:ok) if request.request_method == "OPTIONS"
end

其次,手工设定jQuery的headers:

jQuery.ajaxSetup({
  headers: {"X-Requested-With": "XMLHttpRequest"}
});

最后,设置你的路由config/routes.rb:

match '*all' => 'application#cor', :constraints => {:method => 'OPTIONS'}

这样就OK了。如果还有什么问题可以私信我。

ps:下列浏览器支持CORS:

  • IE >= 8 (with caveats)
  • Firefox >= 3
  • Safari: full support
  • Chrome: full support
  • Opera: no support