gpt4 book ai didi

mysql - 将 React 对象插入 sequelize/MySQL 数据库时遇到问题

转载 作者:行者123 更新时间:2023-12-03 22:34:54 25 4
gpt4 key购买 nike

我的前端和后端已连接,但它没有从 React 表单将值输入到我的 MySQL 数据库中。当我控制台记录从我的 React 应用程序获得的响应时,它会记录

{name: "han solo", email: "han@virginia.edu", message: "fsbfbsf"}

但我的数据库将结果记录为
{id: 4, updatedAt: "2020-05-28T03:11:31.983Z", createdAt: "2020-05-28T03:11:31.983Z"}

我的数据库模型是:
module.exports = function(sequelize, DataTypes) {
var Messages = sequelize.define("Messages", {
name: DataTypes.STRING,
email: DataTypes.STRING,
message: DataTypes.STRING
});
return Messages;
};

我的发帖路线是:
 // POST route for saving a new Message
app.post("/api/messages", function(req, res) {
console.log(req.body);
db.Messages.create({
name: req.body.name,
email: req.body.email,
message: req.body.message
}).then(function(dbMessages) {
// We have access to the new Message as an argument inside of the callback function
res.json(dbMessages);
});
});

我前端的 handleFormSubmit 函数是:
handleFormSubmit = e => {
e.preventDefault();

if (
this.state.name === "" ||
this.state.email === "" ||
this.state.message === ""
) {
this.setState({
formError: true
});
return false;
} else {
this.setState({
formError: false
});
const obj = {
name: this.state.name,
email: this.state.email,
message: this.state.message
};
console.log(obj);
axios
.post(url, {obj})
.then(res => console.log(res.data))
.catch(error => this.setState({ error: error.message }));

this.setState({
name: "",
email: "",
message: ""
});
}
};

似乎默认值正在插入,但不是来自 React 表单的输入值,而是表单值控制台记录为对象

最佳答案

弄清楚了。我必须将值绑定(bind)到状态,并且我将 obj 声明为 {obj} 而不是 obj。更正如下

 constructor(props) {
super(props);
this.getName = this.getName.bind(this);
this.getEmail = this.getEmail.bind(this);
this.getMessage = this.getMessage.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);




axios
.post(url, obj)
.then(res => console.log(res.data))
.catch(error => this.setState({ error: error.message }));

关于mysql - 将 React 对象插入 sequelize/MySQL 数据库时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62056596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com