我有一个带有rails后端的webpack前端。它们在不同的端口上运行,我相信当我尝试将表单数据发布到我的某个rails控制器端点时,这会导致我出现问题。我用Google搜索了几个小时,我感到很沮丧。我不知道为什么我不能发送帖子请求。这是我的ajax请求:
handleSubmit(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3000/api/v1/organizations/",
data: {
organization: {
name: $('#name').val(),
email: $('#email').val(),
description: $('#orgDescription').val(),
password: $('#password').val(),
password_confirm: $('#password_confirm').val(),
}
},
success: function(data){
debugger
}, error: function(data){
debugger
}
});
}
这是我的rails控制器
def create
debugger
organization = Organization.new organization_params
if organization.save
render json: {organization: organization}, status: :ok
else
render json: {error: organization.errors.full_message}, status: :bad_request
end
end
这是每次发送请求的方式:
Started GET "/api/v1/organizations/?callback=jQuery311014517798618579714_1486919266215&organization%5Bname%5D=asd&organization%5Bemail%5D=asdf&organization%5Bdescription%5D=asdf&organization%5Bpassword%5D=[FILTERED]&organization%5Bpassword_confirm%5D=[FILTERED]&_=1486919266216" for 127.0.0.1 at 2017-02-12 10:07:51 -0700
Processing by OrganizationsController#index as JSON
Parameters: {"callback"=>"jQuery311014517798618579714_1486919266215", "organization"=>{"name"=>"asd", "email"=>"asdf", "description"=>"asdf", "password"=>"[FILTERED]", "password_confirm"=>"[FILTERED]"}, "_"=>"1486919266216"}
我唯一可以想到的是我的开发服务器在端口5000上运行而我的rails服务器在3000上运行。有人可以告诉我我做错了吗?
答案 0 :(得分:2)
您需要configure some CORS into your application并停止使用JSONP进行POST请求,因为you can't POST using JSONP。
安装gem rack-cors
将gem 'rack-cors', :require => 'rack/cors'
添加到Gemfile
,运行bundle install
并尝试config/application.rb
的松散配置:
# Rails 3/4
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
# Rails 5
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
您应该考虑在生产环境中进行更好的配置。