簡體   English   中英

在 ReactJs 中使用 NodeJS API 登錄失敗

[英]Failed Login Using NodeJS API in ReactJs

我正在使用 Nodejs 和 Express-session 在 ReactJs 中進行簡單的用戶登錄。 我遇到了前端(React 登錄頁面)無法正常工作的問題。 這是我在 Login.js 中使用的 Fetch API:

  SubmitLogin (event) {
    event.PreventDefault();
    debugger;
    fetch('http://localhost:4000/login', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type' : 'application/json'
      },
      body : JSON.stringfy (this.state)
    }).then((Response) => Response.json())
    .then((result) => {
      console.log(result);
      if (result.Status === 'Invalid')  
          alert('Invalid User');  
        else  
          this.props.history.push({Home});
            alert('Login Sucessfull');
    })
    console.log(this.state);
    alert("test input login")
  }

為了連接到后端,我添加了 server.js,其編碼如下:

app.post('/login', jsonParser, (req, res) => {
    var username = req.body.username;
    var password = req.body.password;
    if (username && password) {
        dbConn.query(`SELECT * FROM user_tbl WHERE username = ? AND password = ?`, [username, password], (err, results, fields) => {
            if (results.length > 0) {
                req.session.loggedin = true;
                req.session.username = username;
        res.redirect('/home');
        console.log(results)
            } else {
                res.send('Incorrect Username and/or Password!');
            }           
            res.end();
        });
    } else {
        res.send('Please enter Username and Password!');
        res.end();
    }
});

app.get('/home', (req, res) => {
    if (req.session.loggedin) {
        res.send('Welcome back, ' + req.session.username + '!');
    } else {
        res.send('Please login to view this page!');
    }
    res.end();
});

我已經使用郵遞員測試了后端,並且它正在工作。 請幫我提供一些建議,以及如何放置 console.log 來查找 Login.js 中的錯誤。 感謝幫助

郵遞員的結果: 在此處輸入圖片說明

更改Response.json()Response.text()因為你是返回text響應不json ,你可以添加catch塊來處理錯誤。

我可以在您的代碼中看到您在Postman中使用Content-Type application/x-www-form-urlencoded ,在fetch調用中使用application/json 在兩個請求中使用相同的Content-Type

SubmitLogin(event) {
    event.PreventDefault();
    fetch('http://localhost:4000/login', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringfy(this.state)
    }).then((Response) => Response.text())
    .then((result) => {
        console.log(result);
        if (result.Status === 'Invalid')
            alert('Invalid User');
        else
            this.props.history.push({ Home });
        alert('Login Sucessfull');
    }).catch(error => {
        console.error(error)
    })
    console.log(this.state);
    alert("test input login")
}

您可以更改代碼以使用async/await以獲得更好的可讀性。

async SubmitLogin(event) {
    event.PreventDefault();
    try {
        let response = await fetch('http://localhost:4000/login', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringfy(this.state)
        });
        let result = await  response.text();
        console.log(result);
        if (result.Status === 'Invalid')
            alert('Invalid User');
        else
            this.props.history.push({ Home });
        alert('Login Sucessfull');
    } catch (error) {
        console.error(error.message);
    }
    console.log(this.state);
    alert("test input login")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM