jsonreactjspaw

Error when passing json object from react frontend to rails api


I'm trying to send my form data to rails api from my react frontend but this happens

This is my react code to handle form data

constructor(props) {
  super(props);
  this.user= {};
  this.state = this.getInitialState();
}

getInitialState = () => {
     const initialState = {
       email: "",
       password: ""
     };
     return initialState;
 }

change = e => {
  this.setState({
    [e.target.name]: e.target.value
  });
};

onSubmit = (e) => {
  e.preventDefault();
  this.user = JSON.stringify(this.state)
  this.user = "{\"user\":" + this.user + "}"
  console.log(this.user);
  fetch('http://localhost:3001/v1/users', {
    method: 'POST',
    body: this.user
  }).then(function(response) {
    console.log(response.json());
  })

  this.setState(this.getInitialState());
}

This code gives the following string in console:

{"user":{"email":"test@user.com","password":"password123."}}

Rails:

class V1::UsersController < ApplicationController

def create

@user = User.new(user_params)

if @user.save
  render :create
else
  head(:unprocessable_entity)
 end
end
private

 def user_params
  params.require(:user).permit(:email, :password, :password_confirmation)
 end
end

Doing the same on PAW gives positive results

PAW

Please help. I've been trying to fix this for 2 days now.

Thank you in advance.


Solution

  • The problem is here

    this.user = "{\"user\":" + this.user + "}"
    

    It just look like json,but it's actually a string.You could use typeof to check it.

    console.log(typeof this.user) //string
    

    There are many options to solve this problem.Here is an example.

    const users = {
      user: user
    }
    console.log(users)
    const user_json = JSON.parse(JSON.stringify(users))
    console.log(typeof user_json)