Reputation: 1
I am currently working on a project using react and ruby on rails. My goal right now is to send a post request using fetch to create and store my user in my backend api on submission of my react form. My problem is, the backend isn't receiving my data correctly, resulting in a 406 error. I feel like i've tried everything, i'm going crazy, help.
REACT CODE:
form-
<form onSubmit={handleSubmit}>
<label>Name:</label>
<input type="text" required value={name} onChange={handleNameChange} name="name" placeholder="name"/>
<label>Password:</label>
<input type="password" required value={password} onChange={handlePasswordChange} name="password" placeholder="password"/>
<input type="submit" value="Create Account"/>
</form>
methods -
const [name, setName] = useState("")
const [password, setPassword] = useState("")
const handleNameChange = (e) => {
setName(e.target.value);
}
const handlePasswordChange = (e) => {
setPassword(e.target.value);
}
const handleSubmit = (e) => {
e.preventDefault();
const data = {name, password}
fetch("http://localhost:3000/users", {
method: 'POST',
body: JSON.stringify(data),
headers: {
Content_Type: "application/json",
}
})
RAILS CODE:
users controller-
def create
user = User.create(user_params)
if user.valid?
payload = {user_id: user.id}
token = encode_token(payload)
render json: { user: user, jwt: token }
else
render json: { error: 'failed to create user' }, status: :not_acceptable
end
end
private
def user_params
params.permit(:name, :password)
end
error - backend error
Upvotes: 0
Views: 984
Reputation: 1470
It looks like user.valid?
returns false
, so your else
statement kicks in:
render json: { error: 'failed to create user' }, status: :not_acceptable
The status: :not_acceptable
generates the 406
error.
You should probably include the reason why user is not valid, and return a bad request response instead:
render json: { error: user.errors.full_messages}, status: :bad_request
Upvotes: 1