首页 > 解决方案 > 将 json 对象从反应前端传递到 rails api 时出错

问题描述

我正在尝试将我的表单数据从我的反应前端发送到 rails api,但这种情况发生了

这是我处理表单数据的反应代码

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());
}

此代码在控制台中提供以下字符串:

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

导轨:

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

在 PAW 上做同样的事情会产生积极的结果

爪子

请帮忙。我已经尝试解决这个问题 2 天了。

先感谢您。

标签: jsonreactjspaw

解决方案


问题就在这里

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

它看起来像json,但它实际上是一个字符串。你可以使用typeof来检查它。

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

有很多选项可以解决这个问题。这里是一个例子。

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

推荐阅读