使用React和passport.js时,Cookie未存储在mysql数据库中

时间:2020-01-05 22:39:57

标签: mysql reactjs express session passport.js

目标:我的应聘应用的后端,它将处理身份验证。

我正在雇用:express和password.js

但是,我只是无法正常工作。我正在使用MySQL护照的本地策略(用于存储会话数据)

使用此示例时: https://github.com/passport/express-4.x-local-example/tree/master/view

  • 身份验证部分有效。
  • 会话数据存储在数据库中也可以正常工作。

当我引入反应时,事情停止了。 React能够与后端进行通信,并且能够完美地从数据库中获取数据。但是,登录时没有会话数据保存到数据库中。

底线-我无法访问应通过护照保存的信息。

index.js

var express = require("express");
var mysql = require("mysql");
var passport = require("passport");
var Strategy = require("passport-local").Strategy;
var session = require("express-session");
var logger = require("morgan");
var MySQLStore = require("express-mysql-session");
var cors = require("cors");



var authRouter = require("./auth");

const pool = mysql.createPool({
  connectionLimit: 10,
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "cercom",
  port: 8889
});

function getConnection() {
  return pool;
}

passport.use(
  new Strategy(function(username, password, cb) {
    const connection = getConnection();

    connection.query(
      "SELECT id, username, password FROM users WHERE username = ?",
      [username],
      function(err, results, fields) {
        if (err) {
          cb(err);
        }

        if (results.length === 0) {
          cb(null, false);
        }
        if (results[0].password === password) {
          cb(null, results[0].id);
        } else {
          cb(null, false);
        }
      }
    );
  })
);

var app = express();

app.use(cors());

const options = {
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "cercom",
  port: 8889
};

var sessionStore = new MySQLStore(options);

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(cookieParser());

app.use(
  session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: false,
    store: sessionStore,
    cookie: { secure: false }
  })
);

app.use(passport.initialize());
app.use(passport.session());

app.use("/auth", authRouter);

app.get("/username", function(req, res, next) {
  const connection = getConnection();

  const id = req.session.passport.user;
  const queryString = "SELECT username FROM users WHERE id = ?";

  connection.query(queryString, [id], function(error, results, fields) {
    if (error) throw error;
    console.log(results[0]);
    res.send(results[0]);
  }); */
});

app.listen(5000, function() {
  console.log("Listening on port 5000");
});

auth.js

var express = require("express");
var router = express.Router();
var passport = require("passport");

router.get("/logout", function(req, res, next) {
  req.logout();
  req.session.destroy();
});

router.post(
  "/login",
  passport.authenticate("local", { session: true }),
  function(req, res) {
     console.log(req.session);
  }
);

passport.serializeUser(function(user_id, cb) {
  cb(null, user_id);
});

passport.deserializeUser(function(user_id, cb) {
  cb(null, user_id);
});

module.exports = router;

Form.js

import React, { useState } from "react";

const Form = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = e => {
    e.preventDefault();

    const data = {
      username: username,
      password: password
    };

    fetch("/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify(data)
    })
      .then(function(response) {
        if (response.status >= 400) {
          throw new Error("Bad response from server");
        }
        return response.json();
      })
      .then(function(response) {
        console.log(response);
      })
      .catch(function(err) {
        console.log(err);
      });
  };

  const handleLogout = e => {
    e.preventDefault();

    fetch("/auth/logout", {
      method: "GET",
      headers: { "Content-Type": "application/json" }
    })
      .then(function(response) {
        if (response.status >= 400) {
          throw new Error("Bad response from server");
        }
        return response.json();
      })
      .then(function(response) {
        console.log(response);
      })
      .catch(function(err) {
        console.log(err);
      });
  };

  return (
    <form onSubmit={handleSubmit} method="POST">
      <label>Username</label>
      <input
        type="text"
        name="username"
        onChange={e => setUsername(e.target.value)}
        value={username}
      />
      <label>Password</label>
      <input
        type="password"
        name="password"
        onChange={e => setPassword(e.target.value)}
        value={password}
      />
      <div>
        <button>Submit</button>
        <button onClick={handleLogout}>Logout</button>
      </div>
    </form>
  );
};

export default Form;

我希望passport.js是使身份验证工作最简单的方法。如果您对使用其他类型的后端有任何建议,从而使身份验证不那么麻烦,那我就耳熟能详。

0 个答案:

没有答案