I have a React Login component running on localhost:3000
. It returns a form which, on submit, uses JS fetch()
to post its information to SessionsController in a rails api which runs on localhost:3001
. I've alternated between using a FormData object and custom json; I run into the same problems either way. I've gotten rid of CORS errors in the console by using 'rack-cors', but I'm still having problems accessing the posted information in my SessionController's create
action. This is all I have in params when I throw a binding.pry into it:
[1] pry(#<SessionsController>)> params
=> <ActionController::Parameters {"controller"=>"sessions",
"action"=>"create"} permitted: false>
------- How do I get hold of my username and password? ----------
Login Component:
import React from 'react'
const Login = () => {
return(
<div>
<h1>Login</h1>
<form id="login-form" onSubmit={(event) => postSession(event)}>
<label htmlFor="username">Username </label><br/>
<input type="text" id="username"/><br/>
<label htmlFor="password">Password </label><br/>
<input type="password" id="password"/><br/>
<input type="submit" value="Login"/>
</form>
</div>
)
}
const postSession = (event) => {
event.preventDefault()
fetch('http://localhost:3001/sessions',
{
header: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
body: new FormData(document.getElementById("login-form"))
}
)
.then((response) => {console.log("Post Session Response: ", response)})
.catch((error) => {console.log("Error in the Post Session fetch: ", error)})
}
export default Login
config/application.js:
module Geohunter2
class Application < Rails::Application
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :patch, :options]
end
end
end
end
You need name
attributes on your form inputs:
<input type="text" id="username" name="user[username]"/><br/>
...
<input type="text" id="password" name="user[password]"/><br/>
Then you'll have access to params[:user][:username] params[:user][:password]
in your controller.
Assuming you're using strong_params
in a newer version of Rails (4+), you'll also need something like this in your controller action.
def new # or whatever action you're posting
Session.create(user_params)
end
private
def user_params
params.require(:user).permit(:username, :password)
end