【问题标题】:post data using form works, but fetch API's not working in my case使用表单发布数据,但在我的情况下获取 API 不起作用
【发布时间】: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


    【解决方案1】:
    const res = axios.post('/api/register', options) 
    

    我认为你错过了在 axios post call 之前使用 await

    在帖子调用中添加等待

    const res = await axios.post('/api/register', options) 
    

    【讨论】:

      【解决方案2】:

      你想要的是把这个表单转换成一个反应组件? 最好的方法是控制字段进入状态,然后单击提交按钮通过axios 发送它

      类似这样的:

      import React, { useState } from "react";
      import { Form, InputGroup, Button } from "react-bootstrap";
      import axios from "axios";
      
      const getInitialState = () => ({
        name: "",
        email: "",
        password: ""
      });
      
      export default function App() {
        const [formData, setFormData] = useState(getInitialState());
        const handleSubmit = async (data) => {
          const options = {
            method: "POST",
            body: JSON.stringify(data),
            headers: {
              "Content-Type": "application/json"
            }
          };
          return axios.post("/api/register", options);
        };
      
        const handleChange = (field) => (e) => {
          const { value } = e.target;
          setFormData({
            ...formData,
            [field]: value
          });
        };
      
        return (
          <Form
            onSubmit={(e) => {
              e.preventDefault();
              handleSubmit(formData);
            }}
          >
            <Form.Group controlId="validationCustom01">
              <Form.Label>Full Name</Form.Label>
              <Form.Control
                type="text"
                placeholder="Full Name"
                value={formData.name}
                onChange={handleChange("name")}
              />
            </Form.Group>
      
            <Form.Group controlId="validationCustomUsername">
              <Form.Label>Username</Form.Label>
              <InputGroup>
                <Form.Control
                  type="email"
                  placeholder="Email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange("email")}
                />
              </InputGroup>
            </Form.Group>
            <Form.Group controlId="validationCustom04">
              <Form.Label>Password</Form.Label>
              <Form.Control
                type="password"
                placeholder="Password"
                name="password"
                value={formData.password}
                onChange={handleChange("password")}
              />
            </Form.Group>
            <Button type="submit" className="button bg-success">
              Submit
            </Button>
          </Form>
        );
      }
      

      【讨论】:

        猜你喜欢
        • 2013-05-06
        • 1970-01-01
        • 2021-01-07
        • 1970-01-01
        • 1970-01-01
        • 2013-12-09
        • 2012-10-09
        • 1970-01-01
        • 2018-01-05
        相关资源
        最近更新 更多