Error when passing json object from react frontend to rails api

Kshitij Sinha

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.

Root

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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Rails API not returning JSON to React frontend

React Hook useState doesnt work when I try passing in a JSON object fetched from an API request

Keep formatting of object when passing EJS object from backend to frontend

Getting Too many requests error when trying to fetch data from API on NodeJS backend, but works on React frontend

TypeScript React error when passing to context object

Getting NoMethodError (undefined method `id' for nil:NilClass) on Rails Json API when trying to create new article from rails frontend site

Displaying error messages from Node API on FrontEnd console (React App)

passing decimals to REST API from multilingual frontend

Unable to receieve the body object from the react frontend to backend(express) api, while it works fine when submit using postman

req.body.jobId shows undefined when passing JobID from a React&Redux frontend to a NodeJS backend?

Authenticated requests for an Rails API backend and React frontend fail when app deployed to Heroku

Passing JSON Object to React Hook

Lumen API returns 422 error when passing body as JSON

React get inner JSON object from api

Passing a file from React/TypeScript to C# API causes error: "The JSON value could not be converted to System.Byte[]"

React frontend response error from flask backend

Object of objects JSON response from Django backend to React-Redux frontend

Accses json data from API to frontend Reactjs

React Native - "Undefined is not an object" error when render a screen that take data from API

Passing json object to db as 'payload' -rails postgrel

React JS Unexpected end of JSON input error when binding data from an API

Undefined object when sending a JSON object from Express server into React?

Trying to pull data from params object in Rails API using JSON

Extracting data from json object from API with JavaScript React Native

Passing data from rails controller to react component

Get filename in Rails backend from file upload in React frontend

Typescript React - JSON API Object ":" expected when indexing

Undefined is not an object evaluating route.params.input. ERROR when passing data between components. REACT NATIVE

Error when passing an Object to a function expecting a Dictionnary?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive