简体   繁体   中英

How to signin with ReactJS, NodeJS using MySQL?

I am a beginner developer on ReactJS, I want to signin my form using ReactJS, NodeJS and MySQL.

My class Login is below :

     handleClick(event){
    var self = this;
    var payload={
      "username":this.state.username,
        "password":this.state.password
    }
    axios({
          method: 'post',
          url: '/app/login/',
          data: payload,
          withCredentials: true,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            'Accept': 'application/json',
          }
        })

   .then(function (response) {
     console.log(response);
     if(response.data.code == 200){

    this.props.history.push("http://localhost:5000/brillo#/");
     }
     else{
       swal("Erreur !", "Erreur !", "error");
     }
   })
   .catch(function (error) {
     console.log(error);
   });
  }
  handleredirect(){
    this.props.history.push("/register");
    }
  render() {
    return (
      <div className="app flex-row align-items-center">

                    <Form  method="POST" >

                      <InputGroup className="mb-3">
                        <Input type="text" placeholder="Username" autoComplete="username" value={this.state.username} onChange={e => this.setState({ username: e.target.value })} required/>
                      </InputGroup>
                      <InputGroup className="mb-4">
                        <Input type="password" value={this.state.password} placeholder="Password" onChange={e => this.setState({password: e.target.value })} autoComplete="current-password"   required/>
                      </InputGroup>
                      <Row>
                        <Col xs="6">
                          <Button type="button" color="primary" className="px-4" onClick={(event) => this.handleClick(event)}>Login</Button>
                        </Col>
                        <Col xs="6" className="text-right">
                          <Button color="link" className="px-0">Forgot password?</Button>
                        </Col>
                      </Row>
                    </Form>

      </div>
    );
  }
}

export default Login;

My router :

exports.login = function(req,res){
  var email= req.body.email;
  var password = req.body.password;
 var username = req.params.username;
  connection.query('SELECT * FROM users WHERE username = ?',[username], function (error, results, fields) {
  if (error) {
   res.send({
      "code":400,
      "failed":"error ocurred"
    })
  }else{
    if(results.length >0){
      bcrypt.compare(password, results[0].password, function(err, doesMatch){
        if (doesMatch){
     res.send({
       "code":200,
       "success":"login sucessfull"
         });
      }else{
     res.send({
       "code":204,
       "success":"Email and password does not match"
         });
      }
    });
  }
    else{
      res.send({
        "code":204,
        "success":"Email does not exits"
          });
    }
  }
  });

}

When I run my backend with Postman by posting http://localhost:4000/app/login/ I get :

{
    "code": 204,
    "success": "Email does not exits"
}

But I post with the username and the password that I submitted on the register form and when I run my frontend, I get :

{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config:
{
data:
code:204
success:"Email does not exits"

I want when I click on the login button, it will be redirected to the dashboard page.

How can I resolve it ?

your nodejs router seems not correct, you take from body email ,password ,username but the email is not send by react. Then what you're looking for in your Database, email or username ?

Next in line

connection.query('SELECT * FROM users WHERE username = ?',[username], function...

I think it should be more like :

connection.query('SELECT * FROM users WHERE username = \'' + username + '\'', function...

And by the way, you response is not correct : you should return :

return res.status(500).json({ failed: 'error ocurred'})

and not

res.send({"code":400,"failed":"error ocurred"})

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