简体   繁体   English

抓住快递的回应做出反应

[英]Catch response from express to react

If the password are not matching I am sending a JSON object as a response.如果密码不匹配,我将发送 JSON object 作为响应。 You can see the response in the image below.您可以在下图中看到响应。 I just want this response in my react component in a variable using useState.我只想在我的反应组件中使用 useState 将这个响应放在一个变量中。

//Sign Up post Method
router.post('/signup', async (req, res, next) => {

  const { fullname, username, email, dateOfBirth, gender, password, conPassword } = req.body
  const user = new User({ fullname, username, email, dateOfBirth, gender, password })
  if(password !== conPassword) {
    return (
      res.status(400).json({passMatch: "Password are not Matching"})
    )
  }
  try {
    await user.save()
  } catch (e) {
    console.log(e.message)
    res.send(e.message)
  }

})

在此处输入图像描述

you are returing a promise.您正在退货 promise。 use .then method and collect data when the response is 400.当响应为 400 时,使用.then方法并收集数据。

const [text,setText] = useState('')
.....
let data = // your request to server
data.then(res=>{
 if(res.status ===400){
setText(res.data)
}
})

res.status will return the status of response. res.status 将返回响应的状态。 if it is coming as a error use .catch如果出现错误,请使用.catch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM