I am trying to build a React front end on top of a Rails API and I am currently working on the registration form on React. Below is my attempt at handling the form submission.
const handleSubmit = (evt) => {
evt.preventDefault()
fetch(`http://localhost:3001/users`, {
method: "POST",
headers: {
"Accept": "application/json"
},
body: JSON.parse(JSON.stringify({
email,
password,
first_name,
last_name,
phone_number
}))
})
.then(resp => console.log(resp.json))
setFirst("")
setLast("")
setEmail("")
setPassword("")
setPhone("")
}
However, when I print out the params received from React, it is empty. Below is my Rails User create method.
def create
@user = User.new(user_params)
puts user_params
if @user.save
render json: @user.id, status: :created
UserMailer.welcome_email(@user).deliver_now
else
render json: {errors: @user.errors.full_messages}, status: :unprocessable_entity
end
end
def destroy
@user.destroy
end
I checked here and here and a bunch of other places but they say pretty much the same thing. Wrap the body in JSON.stringify or JSON.parse or both. But it isn't working for me.