无法在会话变量中设置未定义的 属性 'userId'
Cannot set property 'userId' of undefined in session variable
Cannot read set 属性 of 'userId' of undefined 是 Express 框架中遇到的经典错误,此处的文档介绍了如何处理它,但如何解决此问题NestJS 应用程序?
当您收到一条错误消息 Cannot set property 'userId' of undefined
时,您想查看 cookie-session.
发生了什么
您是否安装了 cookie-session?
每当您尝试在用户的会话对象上设置用户 ID 属性 时都会抛出错误,因为该 cookie 中间件未安装或未 运行ning,您未定义.
因此,当您尝试将 属性 设置为未定义时,您会收到此 classic 错误消息。
因此您的 cookie 会话可能未设置。
在简单的 ExpressJS API 中给出了足够的答案,但是如果您正在使用 NestJS 怎么办?好吧,这是解决这个问题的 NestJS 方法。
将以下内容导入您的 app.module.ts
文件:
import { Module, ValidationPipe } from '@nestjs/common';
import { APP_PIPE } from '@nestjs/core';
转到您的提供者列表并进入数组和一个全新的对象:
providers: [
AppService,
{
provide: APP_PIPE,
useValue: new ValidationPipe({
whitelist: true,
}),
},
],
那么这到底有什么作用呢?它说每当我们创建应用程序模块的实例时,自动使用它。将它应用于流向应用程序的每个传入请求,运行 它通过 class 的实例。全局管道就是这样设置的,但是你得把cookiesession中间件设置成全局中间件。
您需要将以下内容导入同一文件:
import { MiddlewareConsumer, Module, ValidationPipe } from '@nestjs/common';
在底部,添加以下内容:
export class AppModule {
configure(consumer: MiddlewareConsumer) {}
}
只要应用程序开始侦听传入流量,就会自动调用配置函数。所以在这里我可以设置一些中间件,这些中间件将 运行 处理每个传入请求。
为此,我们调用或引用 consumer.apply()
像这样:
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(
cookieSession({
keys: ['dfghjkl'],
}),
);
}
}
然后我需要确保在顶部添加 cookie 会话的要求语句:
const cookieSession = require('cookie-session');
并在底部添加:
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(
cookieSession({
keys: ['dfghjkl'],
}),
)
.forRoutes('*');
}
}
这意味着我想对进入应用程序的每个传入请求使用中间件。应该是这样。
Cannot read set 属性 of 'userId' of undefined 是 Express 框架中遇到的经典错误,此处的文档介绍了如何处理它,但如何解决此问题NestJS 应用程序?
当您收到一条错误消息 Cannot set property 'userId' of undefined
时,您想查看 cookie-session.
您是否安装了 cookie-session?
每当您尝试在用户的会话对象上设置用户 ID 属性 时都会抛出错误,因为该 cookie 中间件未安装或未 运行ning,您未定义.
因此,当您尝试将 属性 设置为未定义时,您会收到此 classic 错误消息。
因此您的 cookie 会话可能未设置。
在简单的 ExpressJS API 中给出了足够的答案,但是如果您正在使用 NestJS 怎么办?好吧,这是解决这个问题的 NestJS 方法。
将以下内容导入您的 app.module.ts
文件:
import { Module, ValidationPipe } from '@nestjs/common';
import { APP_PIPE } from '@nestjs/core';
转到您的提供者列表并进入数组和一个全新的对象:
providers: [
AppService,
{
provide: APP_PIPE,
useValue: new ValidationPipe({
whitelist: true,
}),
},
],
那么这到底有什么作用呢?它说每当我们创建应用程序模块的实例时,自动使用它。将它应用于流向应用程序的每个传入请求,运行 它通过 class 的实例。全局管道就是这样设置的,但是你得把cookiesession中间件设置成全局中间件。
您需要将以下内容导入同一文件:
import { MiddlewareConsumer, Module, ValidationPipe } from '@nestjs/common';
在底部,添加以下内容:
export class AppModule {
configure(consumer: MiddlewareConsumer) {}
}
只要应用程序开始侦听传入流量,就会自动调用配置函数。所以在这里我可以设置一些中间件,这些中间件将 运行 处理每个传入请求。
为此,我们调用或引用 consumer.apply()
像这样:
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(
cookieSession({
keys: ['dfghjkl'],
}),
);
}
}
然后我需要确保在顶部添加 cookie 会话的要求语句:
const cookieSession = require('cookie-session');
并在底部添加:
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(
cookieSession({
keys: ['dfghjkl'],
}),
)
.forRoutes('*');
}
}
这意味着我想对进入应用程序的每个传入请求使用中间件。应该是这样。