我当前使用表设置了数据库,并且数据库已正确连接到节点服务器。问题在于,它在执行时会将值存储为null或undefined,这让我感到我没有正确地从表单发送数据。
下面是我的Reactjs组件文件,其中包含表单和句柄函数
import React, {Component} from 'react';
class RegisterComponent extends React.Component {
constructor() {
super();
this.state = {
username: '',
email:'',
password:'',
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = { username:this.state.username, email:this.state.email , password:this.state.password }
fetch('/api/createAccount', { method: 'POST',
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{ 'Content-Type': 'application/json' } })
.then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label htmlFor="username">Enter username</label>
<input id="username" name="username" type="text" />
<label htmlFor="email">Enter your email</label>
<input id="email" name="email" type="email" />
<label htmlFor="password">Enter a password</label>
<input id="password" name="password" type="text" />
<button>Send data!</button>
</form>
);
}
}
export default RegisterComponent;
下面是api请求脚本
app.post('/api/createAccount', function(req, res) {
const username = req.body.username;
const password = req.body.password;
const email = req.body.email;
con.query(`INSERT INTO usertest2 SET username = ? , email = ? , password = ? `, [username , email, password] , function(err, result) {
console.log(username);
if (err) throw err;
res.send(' successfully');
});
});
答案 0 :(得分:3)
您没有更改状态值的功能。做类似的事情:
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
然后将所有输入内容添加到onChange
中
<input id="password" name="password" type="text" onChange={this.handleChange} />