0

我有以下代码库。

尽管使用了 connect-mongo,但 Express-session 似乎并没有持续存在。

(mongoDB、mongoose、express-session、connect-mongo)

我认为这是 cors 问题,因为它似乎在 Postman 上持续存在并添加了以下代码而没有更改/修复。

app.use(cors({credentials:true, origin: 'http://localhost:3000'}));

有人知道这里的问题吗?这是 cors 问题还是 connect-mongo 配置问题?

import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import mongoose from 'mongoose';
import inProgress from './routes/progress';
import Auth from './routes/auth';
import session from 'express-session';
import MongoStore from 'connect-mongo';

dotenv.config();
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(cors({credentials:true, origin: 'http://localhost:3000'}));

const port = 5000;

app.use(express.json());
// tslint:disable-next-line: only-arrow-functions

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open', () => {
  console.log('MongoDB Atlas connection established');
});

app.use(
  session({
    secret: 'secret123',
    store: new MongoStore({
      mongoUrl: uri,
      ttl: 14 * 24 * 60 * 60,
    }),
    resave: false,
    saveUninitialized: true,
    cookie: {
      httpOnly: false,
      secure: false,
      maxAge: 60000,
    },
  })
);

app.use('/progress', inProgress);
app.use('/auth', Auth);

app.listen(port, () => {
  console.log(`Server is running on PORT ${port}`);
  console.log(process.env.ATLAS_URI);
});

模型.ts

import mongoose, { Schema, Document, Model } from 'mongoose';
import bcrypt from 'bcrypt';

interface IUser extends Document {
  username: string;
  password: string;
}

interface IUserModel extends Model<IUser> {
  findUser(username: string, password: string): any;
}
const userSchema = new mongoose.Schema<IUser>({
  username: {
    type: String,
    unique: true,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
});

// tslint:disable-next-line: only-arrow-functions
userSchema.statics.findUser = async function (username, password) {
  const user = await User.findOne({ username });
  if (!user) {
    return;
  }

  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) {
    return;
  }
  return user;
};

userSchema.pre<IUser>('save', async function (next) {
  const user = this;
  if (user.isModified('password')) {
    user.password = await bcrypt.hash(user.password, 8);
  }
  next();
});

const User: IUserModel = mongoose.model<IUser, IUserModel>('User', userSchema);
export default User;

路线.ts

import express, { response } from 'express';
import User from '../models/user-model';
const router = express.Router();

declare module 'express-session' {
  // tslint:disable-next-line: interface-name
  export interface SessionData {
    user: { [key: string]: any };
  }
}

router.post('/signin', async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findUser(username, password);
  if (user) {
    req.session.user = user._id;
    res.json({
      message: 'You were successfully able to login',
      auth: true,
    });
  } else {
    res.json({
      message: 'Unable to login',
      auth: false,
    });
  }
});

router.post('/signup', (req, res) => {
  const user = new User(req.body);
  req.session.user = user._id;
  user
    .save()
    .then((result) => {
      res.json({
        message: 'Successfully created',
        auth: true,
      });
    })
    .catch((err) => {
      res.json({
        message: 'Unable to create account',
        auth: false,
      });
    });
});

router.get('/checkauth', (req, res) => {
  if (req.session.user) {
    res.json({
      auth: true,
      message: 'You are signed in',
    });
  }
  return res.json({
    auth: false,
    message: 'Sign in please.',
  });
});

export = router;

router.post('/logout', (req, res) => {
  if (req.session.user) {
    // tslint:disable-next-line: only-arrow-functions
    req.session.destroy(function(err) {
      console.log(err);
    });
    res.clearCookie('connect.sid');
    return res.json({ msg: 'logging you out' });
  } else {
    return res.json({ msg: 'no user to log out!' });
  }
});

4

0 回答 0