fetch api不发送数据

时间:2018-02-11 13:57:36

标签: javascript node.js fetch-api

我的客户端应用程序发送数据并在到达服务器时显示undefined。我是一个相当新的节点和整体获取api。当我点击前端的按钮时,它应该触发signin()&发送用户名('机器人')&密码(' cookies')但它没有工作,输出显示在终端中未定义。

服务器

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");
      }
   })
}

1 个答案:

答案 0 :(得分:0)

您在前端代码中输入错误。 fetch api有headers字段,而不是header

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