簡體   English   中英

提取api不發送數據

[英]fetch api doesn't send data

我的客戶端應用程序不發送數據,並在到達服務器時顯示undefined 我對node和fetch api整體還很陌生。 當我單擊前端的一個按鈕時,它應該觸發signin()並發送用戶名('robot')和密碼('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:");
      }
   });
});

前端

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

您在前端代碼中輸入錯誤。 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