簡體   English   中英

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

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

我在會話方面遇到問題。 出於某種原因,即使我使用的是 session 中間件,req.session 也是未定義的。 我試圖使用 redis,但無法建立連接。 奇怪的是,出於某種原因,該 cookie 已在 graphql 游樂場中注冊。 所以原因可能是我傳遞請求的方式。

所有類型都是正確的(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));

我在哪里使用 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",
          },
        ],
      };
     }

你需要像這樣傳遞上下文,你對 go 很好

 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',
    },
  },
};

並將配置文件分配給模塊目錄

用戶.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 {}

它將自動使憑據值從“省略”變為“包含”

我只是在傳遞 res 和 req 時忘記了大括號

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM