简体   繁体   English

res.session 未定义 graphql apollo-server-express

[英]res.session undefined graphql apollo-server-express

I am having trouble with sessions.我在会话方面遇到问题。 For some reason, the req.session is undefined even though I'm using the session middleware.出于某种原因,即使我使用的是 session 中间件,req.session 也是未定义的。 I was trying to use redis but I couldn't make the connection work.我试图使用 redis,但无法建立连接。 The strange part is that for some reason the cookie is registered in the graphql playground.奇怪的是,出于某种原因,该 cookie 已在 graphql 游乐场中注册。 So the reason must be in the way I pass the request, probably.所以原因可能是我传递请求的方式。

All the types are correct ( typescript isn't angry with anything ).所有类型都是正确的(typescript 对任何事情都不生气)。

Here's the code from the server.ts这是来自 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));

And where I use the session.我在哪里使用 session。


    @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",
          },
        ],
      };
     }

you need to pass context something like this and you are good to go你需要像这样传递上下文,你对 go 很好

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

also, it's better to do the configuration in the GraphQL config file to include the credentials.此外,最好在 GraphQL 配置文件中进行配置以包含凭据。

graphql.config.ts 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',
    },
  },
};

and assign the config file to the module directory并将配置文件分配给模块目录

user.module.ts用户.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 {}

and it will automatically enable credentials value to be "include" from "omit"它将自动使凭据值从“省略”变为“包含”

I just forgot the curly brackets when passing res and req throw the context我只是在传递 res 和 req 时忘记了大括号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM