gpt4 book ai didi

javascript - 如何从 React 发送表单数据到 express

转载 作者:搜寻专家 更新时间:2023-11-01 04:12:45 26 4
gpt4 key购买 nike

我是 React 的新手。我正在尝试从提交中将注册数据发送到我的后端。我试过传统的方法,比如在表单中设置 post 方法和路由,但这似乎不起作用。有没有办法将数据发送到后端,然后在前端接收该数据?

后端路由:路由为localhost:4000/api/users/register

router.post("/register", (req, res) => {
console.log(req.body)
console.log('Hit')

knex.select('*')
.from('users')
.where('email', req.body.email)
.then(function(results) {
knex('users')
.insert([{
first_name: req.body.first_name,
last_name: req.body.last_name,
phone: req.body.phone,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 15)
}])
.returning('id')
.then(function(id) {
req.session.user_id = id;
})
.catch(function(error) {
console.error(error)
});
}
})
.catch(function(error) {
console.error(error)
});
// }
});

React 表单代码:

class Register extends Component {
constructor(props) {
super(props)
this.state = {
first_name: '',
last_name: '',
email: '',
password: '',
phone: ''
}
}

onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}

onSubmit = (e) => {
e.preventDefault();
// get form data out of state
const { first_name, last_name, password, email, phone } = this.state;

fetch('http://localhost:4000/api/users/register' , {
method: "POST",
headers: {
'Content-type': 'application/json'
}
.then((result) => {
console.log(result)
})
})
}
render() {
const { classes } = this.props;
const { first_name, last_name, password, email, phone } = this.state;
return (
<div className="session">
<h1>Create your Account</h1>
<div className="register-form">
<form method='POST' action='http://localhost:4000/api/users/register'>
<TextField label="First Name" name="first_name" />
<br/>
<TextField label="Last Name" name="last_name" />
<br/>
<TextField label="Email" name="email" />
<br/>
<TextField label="Password" name="password" />
<br/>
<TextField label="Phone #" name="phone" />
<Button type='Submit' variant="contained" color="primary">
Register
</Button>
</form>
</div>
</div>
);
}
}

export default Register;

最佳答案

您必须将您的state 中的数据发送到服务器,并且您必须对来自fetch 的响应使用json 方法以便访问它。

fetch('http://localhost:4000/api/users/register', {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(this.state)
})
.then((response) => response.json())
.then((result) => {
console.log(result)
})

关于javascript - 如何从 React 发送表单数据到 express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51115640/

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