Reputation: 232
I have a webpack frontend with a rails backend. They are running on different ports, and I believe this is causing me problems when I am trying to post form data to one of my rails controller end points. I have googled for a few hours and I am getting frustrated. I have no idea why I can't send a post request. here is my ajax request:
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
}
});
}
and here is my rails controller
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
this is how the request is sent every time:
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"}
the only thing I can think is that my dev server is running on port 5000 and my rails server is running on 3000. Can someone tell me what I am doing wrong?
Upvotes: 1
Views: 61
Reputation: 4216
You need to configure some CORS into your application and stop using JSONP for POST requests, since you can't POST using JSONP.
Install gem rack-cors
adding gem 'rack-cors', :require => 'rack/cors'
to your Gemfile
, run bundle install
and try a loosy configuration for 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
You should consider a better config on production enviroment.
Upvotes: 2