Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 快速会话:如何将用户详细信息添加到快速会话类型脚本_Node.js_Typescript_Express Session - Fatal编程技术网

Node.js 快速会话:如何将用户详细信息添加到快速会话类型脚本

Node.js 快速会话:如何将用户详细信息添加到快速会话类型脚本,node.js,typescript,express-session,Node.js,Typescript,Express Session,嘿,所以我尝试使用express session和connect mongodb session,TypeScript express/Node Api现在我想做的是,当用户登录时,我将使用express session生成cookie,并自动将cookie持久化到mongodb。现在我遇到的问题是,我想在会话中添加详细信息,即用户信息,以便在持久化用户时,我知道他们的用户名等 现在,当不使用TypeScript时,我可以简单地执行类似的操作,将用户详细信息添加到正在启动的会话中: reques

嘿,所以我尝试使用
express session
connect mongodb session
,TypeScript express/Node Api现在我想做的是,当用户登录时,我将使用express session生成cookie,并自动将cookie持久化到mongodb。现在我遇到的问题是,我想在会话中添加详细信息,即用户信息,以便在持久化用户时,我知道他们的用户名等

现在,当使用TypeScript时,我可以简单地执行类似的操作,将用户详细信息添加到正在启动的会话中:
request.session.user={用户名:'John',id='97Y977C9Q7DW7Y9QW7D9721'}

但是现在在使用TypeScript时,当我尝试执行上述操作时,我遇到了以下错误:\

  • 错误:类型“会话和部分”上不存在属性“用户”
下面的代码:这是我为快速会话连接mongodb会话

const store = MongoStore(expressSession);
const mongoURI = process.env.mongoURI;
const mongoStore = new store({
  collection: 'usersessions',
  uri: mongoURI,
  expires: 10 * 60 * 60 * 24 * 1000
});

app.use(
  expressSession({
    name: '_sid',
    secret: process.env.session_secret,
    resave: false,
    saveUninitialized: false,
    store: mongoStore,
    cookie: {
      httpOnly: true,
      maxAge: 10 * 60 * 60 * 24 * 1000,
      secure: process.env.NODE_ENV === 'production'
    }
  })
);
下面的代码是我的登录方法控制器

 SignIn(request: Request, response: Response) {
    const form = new Formidable.IncomingForm();

    try {
      form.parse(request, async (error, fields, files) => {
        if (error) {
          return response.status(500).json({
            msg: 'Network Error: Please try again later'
          });
        }

        const { username, password } = fields;

        if (!username || !password) {
          return response.status(400).json({ msg: 'All fields are required' });
        }

        const user: any = await userModel.findOne({
          usernam: username
        });

        if (!user) {
          return response.status(404).json({
            msg: 'Account with this username does not exist'
          });
        }

        const hashedPassword = user.password;
        const isPasswordValid = await Bcrypt.compare(password, hashedPassword);

        if (!isPasswordValid) {
          return response.status(400).json({ msg: 'Invalid credentials' });
        }

        const isUserSessionExisting = await userSession.findOne({
          'session.user.username': username
        });
        if (isUserSessionExisting) {
          return response
            .status(200)
            .json({ msg: 'Account already logged in' });
        }
        const userSessionObj = {
          username: user.username,
          id: user._id
        };

        request.session.user = userSessionObj; //This is where the error is coming 
        return response.status(200).send(request.sessionID);
      });
    } catch (error) {
      return response
        .status(500)
        .json({ msg: 'Network Error: Please try again later' });
    }
  }

如何解决此问题

您有两种方法来声明会话

import {Request} from "express"
type Req=  Request & { session: Express.Session }; // this will be merges

这是会话接口:

interface Session extends SessionData {
      id: string;
      regenerate(callback: (err: any) => void): void;
      destroy(callback: (err: any) => void): void;
      reload(callback: (err: any) => void): void;
      save(callback: (err: any) => void): void;
      touch(): void;
      cookie: SessionCookie;
    }
如您所见,没有用户属性。因为我们通常在cookie中存储一个唯一的标识符,即数据库id。因为用户名将来可以更改,但用户的数据库id或如果您正在执行google oauth身份验证,则用户的google id不会更改。存储id就足够了。但是,如果仍然要将用户对象附加到会话,请创建一个新的用户界面

interface User{
  username: string;
  id:string 
}


type NewSession=Express.Session & User

declare global {
  namespace Express {
    interface Request {
      // currentUser might not be defined if it is not logged in
      session: NewSession;
    }
  }
}

你能试着从“快速会话”导入{Session}吗;声明模块'express session'{interface session{user:user;}}}非常感谢您刚刚尝试了这个模块,它工作了,非常感谢
interface User{
  username: string;
  id:string 
}


type NewSession=Express.Session & User

declare global {
  namespace Express {
    interface Request {
      // currentUser might not be defined if it is not logged in
      session: NewSession;
    }
  }
}