使用axios进行发布请求并获取响应

问题描述 投票:0回答:3

从axios响应中获取数据在console.logged中返回未定义的值我尝试了很多方法但响应总是显示未定义这是usersdata const userdatas = [{id:1,firstname:“Leanne”,lastname:“Gram”,password :“123”,电话:“9474211442”} **

客户

handleSubmit=(e)=>{ 
              alert(this.state.Firstname)
              e.preventDefault();
              axios.post('http://localhost:3001/login', {
                lastname: JSON.stringify(this.state.Lastname),
                firstname: JSON.stringify(this.state.Firstname),
                password:JSON.stringify(this.state.password),
                phoneno:JSON.stringify(this.state.phoneno)

              }).then(res=>alert(res.data.id))



            }

]

表达

 const userdatas=[  {id: 1,firstname: "Leanne",lastname:"Gram",password: "123",phone:"9474211442"}**

app.post('/login',(req,res)=>{
let logindetail={firstname:req.body.firstname,
password:req.body.password}
logindetail.firstname=logindetail.firstname.replace(/['"]+/g, '')
logindetail.password=logindetail.password.replace(/['"]+/g, '')


var count = Object.keys(userdatas).length;

for(var i=0;i<count;i++)
{
if(logindetail.firstname===userdatas[i].firstname&&logindetail.password===userdatas[i].password)
{
  res.json(userdatas[i])
}

}

});
reactjs axios
3个回答
0
投票

在你的Express部分,userdatas似乎是一个对象,但你试图在你的res.json调用中查找它像一个数组。您需要像设置计数值时那样将它包装在Object.keys中。


0
投票

看到你在后端收到的内容似乎不对,我会重新审视前端请求。恕我直言,你应该只对你要包装的整个对象进行一次JSON.stringify调用,而不是每个prop的单独调用。试试看,然后看看后端收到了什么。


-1
投票

首先,userdatas是一个对象,你试图像在数组中一样访问它的值。其次你确定循环中的if条件一次得到满足吗?因为您不能对单个请求进行多次响应。在循环时在变量中构建单个响应主体。循环结束后发送它。

for (var i = 0; i < count; i++) {
  if (
    logindetail.firstname === userdatas[i].firstname &&
    logindetail.password === userdatas[i].password
  ) {
    res.json(userdatas[i]);
  }
}

把它改成这样的东西

   let result = [];
    for (var i = 0; i < count; i++) {
      if (***your corrected condition***) {
        result = userdatas[i];
      }
    }

   res.send(result);
© www.soinside.com 2019 - 2024. All rights reserved.