简体   繁体   中英

Promise rejected in POST login using fetch API in reactjs and Nodejs

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: 在此处输入图片说明

hopefully my question is clear.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM