简体   繁体   English

提取api不发送数据

[英]fetch api doesn't send data

My client side app doesn't send the data and show undefined when it reaches the server. 我的客户端应用程序不发送数据,并在到达服务器时显示undefined I'm fairly new to node and fetch api as a whole. 我对node和fetch api整体还很陌生。 When I click a button on the front end, it should fire the signin() & send username('robot') & password('cookies') but it doesn't work and output show undefined in the terminal. 当我单击前端的一个按钮时,它应该触发signin()并发送用户名('robot')和密码('cookies'),但它不起作用,并且输出在终端中显示未定义。

SERVER 服务器

var database = [
  {
    name: 'robot',
    password: 'cookies'
  }
];

app.post('/signin',(req,res)=>{
   let username = req.body.username;
   let password = req.body.password;

   database.map((user,i) =>{
      if (username === database[i].name &&
          password === database[i].password) {
            res.json('success');
      }else{res.json("Login fail");console.log(req.body.username+":user:",req.body.username+":pass:");
      }
   });
});

FRONT-END 前端

signIn() {
   console.log('SignIn function called');console.log("Password: ",this.state.password);console.log("Username: ",this.state.username);

   fetch('http://localhost:3000/signin',{
      method:'post',
      header:{'Content-Type':'application/json'},
      body: JSON.stringify({
         username:this.state.username,
         password:this.state.password
      })
   })
   .then(r => r.json())
   .then(d => {
      if (d === 'success'){
        console.log("Login succesfull");
      }else{
        console.log("Failed");
      }
   })
}

You have typing error in front-end code. 您在前端代码中输入错误。 fetch api has headers field, not header . fetch api具有headers字段,而不是header

fetch('http://localhost:3000/signin',{
   // other code
   headers: {
     'Content-Type':'application/json'
   },
})

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

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