0

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

2
  • 1
    Probably because the header name isn't correct, can you try to change it to { "Content-Type" : "application/json" } instead? Commented Aug 1, 2021 at 23:24
  • @nasser17 AND just like that you saved me. Thank you. Commented Aug 2, 2021 at 19:34

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.