0

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":"[email protected]","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.

1
  • Judging from your error message,I think your rails don't receive your json data from the frontend.So try add "p params[:user]" to check date. Commented Oct 29, 2018 at 7:57

1 Answer 1

0

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

1 Comment

Well this didn't quite work but this did. const data = JSON.stringify({user: this.state}) But thanks for pointing out that data type. completely missed that

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.