简体   繁体   中英

fetch api doesn't send data

My client side app doesn't send the data and show undefined when it reaches the server. I'm fairly new to node and fetch api as a whole. 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.

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('http://localhost:3000/signin',{
   // other code
   headers: {
     'Content-Type':'application/json'
   },
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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