给出一些客户端js
(function(){
var submitEmail = function () {
$("#join").click(function(e){
var email = $("#email").val()
if ( email.length === 0) { return false}
console.log(email)
$.ajax({
crossDomain: true,
type: "POST",
url: "https://www.rubyonrailstutor.com/join.json",
data: {first_name: "hacker", last_name: "github.io", email: "email" },
dataType: "JSON"
})
});
}
submitEmail()
在rails应用程序控制器中给出以下配置
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_headers
private
def set_headers
headers['Access-Control-Allow-Origin'] = 'http://rubyonrailstutor.github.io'
headers['Access-Control-Allow-Methods'] = 'POST'
headers['Access-Control-Allow-Headers'] = '*,x-requested-with,Content-Type,If-Modified-Since,If-None-Match,Auth-User-Token'
headers['Access-Control-Expose-Headers'] = 'ETag'
end
end
在heroku上获得以下行为
2014-03-07T18:17:34.258456+00:00 app[web.1]: Started POST "/join.json" for 99.108.137.170 at 2014-03-07 18:17:34 +0000
2014-03-07T18:17:34.363521+00:00 heroku[router]: at=info method=POST path=/join.json host=www.rubyonrailstutor.com request_id=96ce40a0-652a-4d40-ab29-a364e47d4815 fwd="99.108.137.170" dyno=web.1 connect=3ms service=113ms status=200 bytes=897
2014-03-07T18:18:14.482579+00:00 app[web.1]: Started POST "/join.json" for 99.108.137.170 at 2014-03-07 18:18:14 +0000
2014-03-07T18:18:14.491328+00:00 heroku[router]: at=info method=POST path=/join.json host=www.rubyonrailstutor.com request_id=cdb3e5dd-b200-4aa4-9fd2-c97688f64f58 fwd="99.108.137.170" dyno=web.1 connect=2ms service=12ms status=200 bytes=897
2014-03-07T18:20:38.956777+00:00 app[web.1]: Started POST "/join.json" for 99.108.137.170 at 2014-03-07 18:20:38 +0000
似乎没有足够的数据传递给服务器,即有数据参数,服务器似乎没有处理任何东西,请求正在进行,然后我不知道发生了什么,我该怎么做才能解决这个问题?
谢谢!答案 0 :(得分:1)
您应该使用rack-cors gem,它可以让您轻松完成。
Rack :: Cors为Rack兼容的Web应用程序提供跨源资源共享(CORS)支持。 CORS规范允许Web应用程序进行跨域AJAX调用
<强> Gemfile.rb 强>:
gem 'rack-cors',
:require => 'rack/cors'
<强>配置/ application.rb中强>
module Sample
class Application < Rails::Application
# other application config
config.middleware.use Rack::Cors do
allow do
origins 'https://www.rubyonrailstutor.com/'
resource %r{/users/\d+.json},
:headers => ['Origin', 'Accept', 'Content-Type'],
:methods => [:put, :delete]
end
end
end
end
您可以找到更详细的用途here。