Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed Login Using NodeJS API in ReactJs

I am working on simple user login in ReactJs with Nodejs and Express-session. I got problem that my front end (React login page) not working. here is the Fetch API that I used in Login.js:

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

for connecting to backend, I added server.js with coded like this :

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

I already tested back end using postman, and it's working. Please help me with some suggestion and how I can put console.log to find the error in Login.js. Thanks for help

the result in postman : enter image description here

like image 732
Shinichi1988 Avatar asked Nov 27 '25 11:11

Shinichi1988


1 Answers

Change the Response.json() to Response.text() as you are returning text in response not json, and you could add the catch block to handle the errors.

I can see in your code that you are using Content-Type application/x-www-form-urlencoded in the Postman and application/json in the fetch call. use same Content-Type in both request.

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

You could change your code to use async/await for better readability.

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")
}
like image 62
Sohail Ashraf Avatar answered Nov 29 '25 01:11

Sohail Ashraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!