【发布时间】:2021-04-17 01:42:17
【问题描述】:
我正在开发 React 项目,目前正在制作注册表单。
使用 Form 发布表单数据效果很好。但是当我使用onSubmit={handleSubmit} 并使用诸如axios 或只是fetch 之类的获取API 时,它停留在axios.post(url,options)。我实际上需要Post 用户数据,如果用户已经存在,则需要在客户端打印错误消息。
注册组件 1:
<Form method='POST' action="http://localhost:5000/api/register">
<Form.Group controlId="validationCustom01">
<Form.Label>Full Name</Form.Label>
<Form.Control
type="text"
placeholder="Full Name"
/>
<Form.Control.Feedback>Looks good!</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="validationCustomUsername">
<Form.Label>Username</Form.Label>
<InputGroup >
<Form.Control
type="email"
placeholder="Email"
name="email"
/>
</InputGroup>
</Form.Group>
<Form.Group controlId="validationCustom04">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
name="password" />
</Form.Group>
<Button type="submit" className='button bg-success' >Submit</Button>
</Form>
Server.js
app.post('/api/register', async (req,res) =>
{
let {name,email,password} =req.body
if(password.length >=8 )
{
let hashpassword = await bcrypt.hash(password,10);
pool.query(`SELECT * FROM USERSDATA WHERE EMAIL= $1 `, [email],
(err,results) =>
{
if(err){
throw err;
};
if(results.rows.length == 0)
{
pool.query(`INSERT INTO USERSDATA (NAME,EMAIL,PASSWORD) VALUES ($1,$2,$3) RETURNING id`,[name,email,hashpassword],
(err,results) =>
{
if(err)
{
throw error;
}
res.redirect("http://localhost:3000/login");
}
);
}
else{
res.status(400)
//Here i want to send error as response and to process this error at frontend
res.redirect("http://localhost:3000/register")
}
}
);
}
});
我尝试使用handleSubmit 处理表单提交,并提出了不同的获取发布请求,但在使用代码时遇到了不同类型的错误。给出了我使用的一种技术。
const handleSubmit = async e => {
e.preventDefault()
const options = {
method: "POST",
body:JSON.stringify(data),
headers:{
'Content-Type':'application/json'}}
const res = await axios.post('/api/register', options)
// here (above) i got many errors while playing different techniques like different fetch API's
}}
return(
<Form onSubmit={handleSubmit} >
...
...
</Form>
)
还有其他方法可以让我在 React Component 中访问 server response message 吗?因为这花了我 8 个小时,但仍未解决。
【问题讨论】:
标签: javascript node.js reactjs express axios