json - 将 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 天了。
先感谢您。
解决方案
问题就在这里
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)
推荐阅读
- google-app-engine - 通过云外壳部署应用程序引擎挂起没有错误
- mysql - 如果没有结果,MySQL 将返回 NULL
- c++ - void 函数可以传递值参数吗?
- php - php中数组到字符串的转换问题
- excel - VBA在命令按钮上显示/隐藏图像或形状单击事件对数据进行排序
- node.js - 如何使用 NodeJs POST 请求下载分块文件?
- reactjs - AWS AppSync 将 Gatsby-Image 流体图像作为外键添加到其他 GraphQL 模型
- vue.js - 使用 Vue Storybook 时无法编译 sass
- java - UFT Eclipse IDE
- meshlab - 无法在 meshlab 中保存四边形网格