首页 > 解决方案 > 初学者反应/护照 - 无法登录

问题描述

我从 Passport 开始,我似乎无法让登录系统工作。

反应代码:

import React, { Component } from 'react';
import 'antd/dist/antd.css';  // or 'antd/dist/antd.less'
import { Card, Col, Row, Icon, Button, Input, Modal } from 'antd';

class App extends Component {

  state = {
    username: undefined,
    password: undefined
  }

  login(username, password) {
      fetch('http://localhost:8080/login', {
        method: 'post',
        headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
      }).then(function(response) {
        console.log("1111", response.json())
      }).then(function(data) {
        console.log("22222", data);
      }).catch((error) => {
          console.log("33333", error)
        });
    }

  render() {
    return (
      <div className="App">

        <Modal
          title="Log in"
          visible={this.state.modalVisible}
          onOk={() => this.setModalVisible(false)}
          onCancel={() => this.setModalVisible(false)}
          footer={null}
          type="primary"
        >
          <Input style={{marginBottom: "10px"}} name="username" onChange={this.onChangeUsername}/>
          <Input style={{marginBottom: "20px"}} name="password" onChange={this.onChangePassword}/>
          <Button style={{width: "100%"}} onClick={() => this.login(this.state.username, this.state.password)}> Login </Button>
        </Modal>

      </div>
    );
  }
}

export default App;

节点后端,由这个 React 组件调用:

app.post("/login", function(request, response) {
  passport.authenticate("local-login", function(err, user, info) {
    if (err) {
      return console.log(err);
    }
    if (!user) {
      return response.send(false);
    }
    request.logIn(user, function(err) {
      if (err) {
        return console.log(err);
      }
      checkLogIn(request, response);
      return response.send(true);
    });
  })(request, response);
});

Passport.js

 passport.use(
  'local-login',
  new LocalStrategy({
   usernameField : 'username',
   passwordField: 'password',
   passReqToCallback: true
  },
  function(req, username, password, done){
   connection.query("SELECT * FROM tbl_users WHERE username = ? ", [username],
   function(err, rows){
    if(err)
     return done(err);
    if(!rows.length){
     return done(null, false, req.flash('loginMessage', 'No User Found'));
    }
    if(!bcrypt.compareSync(password, rows[0].password))
     return done(null, false, req.flash('loginMessage', 'Wrong Password'));

    return done(null, rows[0]);
   });
  })
 );

在 Chrome 控制台中,这就是我得到的:

1111 承诺 {} App.js:30
22222 未定义

如何修改此代码,以便在用户凭据正确的情况下返回用户的用户名,否则 console.log 会返回错误消息?

谢谢!

标签: javascriptnode.jsreactjspassport.js

解决方案


推荐阅读