2

I am working on a simple login using POST Fetch in Reactjs with NodeJs API. The code is working good and redirect the page when we login using correct username and password but the problem is when using fake username. I got the error in console.log with Promise : "Rejected". And I still can not figure it why

Here is the code in login.js

async SubmitLogin(event){
  event.preventDefault();
  //debugger;
  console.log(this.state)
  await fetch(`http://localhost:4000/login`, {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
      },
      body: JSON.stringify(this.state)
  })
  .then ((response) => {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    // then Read the response as json.
    else {
      let result = response.json();
      console.log(result)
      if(result === 'Invalid'){
        console.log(response)
        alert('Invalid User');
        //this.props.history.push('/login');
      }
        else {
          alert('Login Sucessfull');
          this.props.history.push('/home');
        }
    }
  })
  .catch((err) => {
    console.error();
  })
}

in my server.js, I used express-session like this:


//sales login
app.post('/login', jsonParser, (req, res) => { //jsonParser,
    let username = req.body.username;
  let password = req.body.password;
  console.log("req: ",req.body);
    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)
        console.log("req: ", req.body);
            } 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();
});

and this is the result I got in console: enter image description here

hopefully my question is clear.

7
  • The error's pretty clear? Whatever you're getting back is not JSON, so maybe log that to console and see what it actually is. Also, don't use alert, not even for debugging. Use console.log and console.error, which can actually log the real data instead of an often-terrible-toString value. Commented Mar 18, 2020 at 3:45
  • what should I do to fix this error,,, how to getting back JSON? Commented Mar 18, 2020 at 3:51
  • 1
    Consider using JWT and OAuth/OpenID for login. You can do this easily with Passport.js. Besides the fact that it's 2020 and I don't think any site should force you to create a login anymore, you're storing passwords in cleartext, which is a big no-no. Commented Mar 18, 2020 at 4:04
  • 1
    thanks ... I am a new here and still learning in using passport.js Commented Mar 18, 2020 at 4:20
  • 2
    your client code is saying it expects JSON code, but your server is sending plain strings, so either update your server to start sending JSON (e.g. send { status: "success", msg: "..." }) or update your client to expected the response to be text/plain, not application/json. Commented Mar 18, 2020 at 15:07

2 Answers 2

1

I think your response doesnt come json format.You cant parse string to json.

Your response should be like this res.send({success:false , message : "Incorrect Username and/or Password!"})

Sign up to request clarification or add additional context in comments.

Comments

0

After many suggestions and anwers, finally I can figure out how to solved this problem. Here is the code in login.js

  //submit function
  async SubmitLogin(event){
    event.preventDefault();
    console.log(this.state)
    await fetch(`http://localhost:4000/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify(this.state)
    })
    .then ((response) => {
      if(response.status === 401) {
          throw new Error('Unauthorized');
      }
      //return response.json();
    })
    .then((result) => {
      console.log(result);
      this.props.history.push('/home');
      alert('Login Sucessfull');
    })
    .catch((err) => {
      console.log();
    })
  }

and in the backend, I didn't change anything.

Comments

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.