【问题标题】:Error when passing json object from react frontend to rails api将json对象从反应前端传递到rails api时出错
【发布时间】:2018-10-29 01:06:50
【问题描述】:

我正在尝试将表单数据从我的 react 前端发送到 rails api,但 this happens

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

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 上做同样的事情会产生积极的结果

PAW

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

提前谢谢你。

【问题讨论】:

  • 从你的错误信息来看,我认为你的 Rails 没有从前端收到你的 json 数据。所以尝试添加“p params[:user]”来检查日期。

标签: json reactjs paw


【解决方案1】:

问题来了

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)

【讨论】:

  • 好吧,这不太奏效,但确实奏效了。 const data = JSON.stringify({user: this.state}) 但感谢您指出该数据类型。完全错过了
猜你喜欢
  • 1970-01-01
  • 2020-12-18
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多