res.session undefined graphql apollo-server-express



我在会话中遇到了麻烦。出于某种原因,要求。会话是未定义的,即使我使用会话中间件。我试图使用redis,但我无法使连接工作。奇怪的是,由于某些原因,cookie是在graphql playground中注册的。所以原因一定是我传递请求的方式,可能。

所有的类型都是正确的(typescript没有生气)。

下面是server.ts

的代码
    import express, { Request, Response } from "express";
    import routes from "./routes";
    import cors from "cors";
    import "reflect-metadata"; 
    import { createConnection } from "typeorm";
    import { ApolloServer } from "apollo-server-express";
    import { buildSchema } from "type-graphql";
    import session from "express-session";
    createConnection()
      .then(async (connection) => {
    console.log("Conexão feita com sucesso");
    
    const app = express();
    app.set("trust proxy", 1);
    
    app.use(cors());
    app.use(
      session({
        name: "qid",
        secret: "keyboard cat",
        resave: false,
        saveUninitialized: true,
        cookie: {
          secure: false,
          maxAge: 1000 * 60 * 60 * 24 * 365 * 10,
          httpOnly: true,
        },
      })
    );
    const apolloServer = new ApolloServer({
      schema: await buildSchema({
        resolvers: [
        ],
        validate: false, // Activate the validation with class-validation module.
      }),
      context: (req: Request, res: Response): Context => ({ req, res, session: req.session }),
      playground: {
        settings: {
          'request.credentials': 'include',
        },
      },
    });
    apolloServer.applyMiddleware({ app });
    app.use(express.json());
    app.use(routes);
    app.listen(3333);
  })
  .catch((error) => console.error(error));

和我在哪里使用会话。


    @Mutation(() => UserResponse)
    async login(
    @Arg("info", () => UserLoginInputType) info: UserLoginInputType,
    @Ctx(){req, res, session}: Context
    ): Promise<UserResponse> {
      const user = await User.findOneOrFail({ where: { email: info.email } });
      const valid = await argon2.verify(user.password, info.password);
      if (valid) {
        
        req.session.userId = user.id;
        
        return {
          user,
        };
      }
      return {
        errors: [
          {
            field: "password",
            message: "Incorrect password",
          },
        ],
      };
     }

我只是忘记了在传递res和req throw context时使用花括号

你需要像这样传递上下文然后你就可以开始了

 context: ({ req, res }): Context => ({
    req,
    res,
    session: req.session,
  }),

此外,最好在GraphQL配置文件中进行配置,以包含凭据。

graphql.config.ts

import { ApolloDriverConfig, ApolloDriver } from '@nestjs/apollo';
import { join } from 'path';
export const GraphQLConfig: ApolloDriverConfig = {
  driver: ApolloDriver,
  debug: true,
  autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
  playground: {
    settings: {
      'editor.theme': 'light', // use value dark if you want a dark theme in the playground
      'request.credentials': 'include',
    },
  },
};

并将配置文件分配到模块目录

user.module.ts

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { TypeOrmModule } from '@nestjs/typeorm';
import { GraphQLConfig } from 'src/config/graphql.config';
import { UserEntity } from 'src/entity/user.entity';
import { UserResolver } from './user.resolver';
import { UserService } from './user.service';
@Module({
  imports: [
    TypeOrmModule.forFeature([UserEntity]),
    GraphQLModule.forRoot(GraphQLConfig),
  ],
  providers: [UserService, UserResolver],
})
export class UserModule {}

,它将自动启用凭据值为"include"从"omit">

最新更新