【问题标题】:How to handle data being sent by Axios post request?如何处理 Axios 发布请求发送的数据?
【发布时间】:2021-08-28 00:20:50
【问题描述】:

我有一个 react 前端和 node.js 后端。

我正在使用 axios 成功发送 POST 请求:

  const [logins, setLogins] = useState({});


  function updateLogins(e) {
    setLogins({...logins, [e.target.name]:e.target.value})
  }

  function submitHandler() {
    console.log(logins)
    axios({
      method: 'post',
      url: 'http://localhost:3001/api/login',
      data: logins
    })
    .then( (res) => {
      console.log(res)
    })
  }

我看到来自我的输入字段的登录信息作为一个对象在控制台中被接收,我想知道采取什么步骤在后端捕获这些数据,然后将其保存到 mongoDB 地图集。 (使用猫鼬)

【问题讨论】:

  • 为什么不显示您现有的接收此请求的后端代码,并显示您尝试将其放入数据库的代码?这个问题实际上应该更多地是关于您在数据库代码中遇到的特定问题,而不是像这样的一般问题。我们不会在这里教你 mongodb(有很多网络资源可以学习那个 db)——相反,人们可以在这里帮助你解决代码中的特定问题。

标签: reactjs mongodb express mongoose axios


【解决方案1】:

因此,如果您在后端收到您的发布请求,您将需要首先对登录字段进行一些错误检查,例如是否填写了所需的每个输入字段等。

确保您已连接到您的 atlas 集群。 how to connect mongoose

在您使用猫鼬的后端,您必须有一个 Schema 来定义您正在输入的数据的“形状”,并为每个文档从您的架构创建一个 Model

这是我使用 node.js、Express.js、mongoose 创建的应用程序中的一些代码,供用户注册。

users.post('/register', async (req, res) => {
    try {
        let { email, password, passwordCheck, username } = req.body
        // ERROR CHECKING
        if( !email || !password || !passwordCheck) {
            return res.status(400).json({msg: "Not all fields have been entered."})
        }
        if(password.length < 5){
            return res.status(400).json({msg: "The password needs to be atleast 5 characters long."})
        }
        if (password !== passwordCheck) {
            return res.status(400).json({msg: "Passwords do not match!"})
        }
        const existingUser = await User.findOne({email: email })
        if (existingUser) {
            return res.status(401).json({msg: "An account with this email already exists"})
        }
        if (!username) {
            username = email
        }

        // Password HASHING
        const salt = await bcrypt.genSalt()
        const passwordHash = await bcrypt.hash(password, salt)
        
        // this is where we create out new User using the User model
        const newUser = new User({
            email,
            password: passwordHash,
            username
        })
        // this is where we tell mongoose to save the newly created document to mongoDB
        const savedUser = await newUser.save()
        res.status(200).json(savedUser)

    } catch (err) {
        res.status(500).json({error: err.message})
    }

})

如果您在连接或创建架构/模型方面需要帮助,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-12
    • 2021-08-11
    • 2022-12-10
    • 1970-01-01
    • 2020-06-05
    • 2022-01-18
    • 2017-08-14
    相关资源
    最近更新 更多