3

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

1 Answer 1

2

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")
}
Sign up to request clarification or add additional context in comments.

3 Comments

yes, I used both. I still cannot catch the error in console. In inspect element of browser I only got this [HMR] Waiting for update signal from WDS... but I think this is not the problem
yes, you're right, I change the content-type in postman, and I got error. how can I solve this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.