无法在 NestJs 响应中设置 cookie。

huangapple go评论60阅读模式
英文:

Can't set cookie in response NestJs

问题

I Have a nestjs graphQL auth microservice and trying to set a http only cookie containing the token, and for some reason setting the cookie doesn't work, i get this error:

{
  "errors": [
    {
      "message": "response.cookie is not a function",
      "path": [
        "login"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "stacktrace": [
          "GraphQLError: response.cookie is not a function",
          "    at downstreamServiceError (/home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:872:12)",
          "    at /home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:577:9",
          "    at Array.map (<anonymous>)",
          "    at sendOperation (/home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:576:38)",
          "    at processTicksAndRejections (node:internal/process/task_queues:95:5)",
          "    at /home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:450:41",
          "    at executeNode (/home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:372:9)",
          "    at /home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:195:27",
          "    at /home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/index.ts:826:28",
          "    at execute (/home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/server/src/requestPipeline.ts:536:22)"
        ],
        "serviceName": "users"
      }
    }
  ],
  "data": null
}

Here is main.ts

async function bootstrap() {
  const app: NestExpressApplication =
    await NestFactory.create<NestExpressApplication>(
      UsersModule,
      new ExpressAdapter(),
    );

  app.use(cookieParser());

  return app.listen(9009);
}

bootstrap();

and this is my auth resolver

@Resolver('Auth')
export class AuthResolver {
  constructor(private authService: AuthService) {}

  @Query('login')
  async login(
    @Res() response: Response,
    @Args('user') user: LoginUserInput,
  ): Promise<LoginResult> {
    // log(res.cookie('test', 33));

    try {
      const result = await this.authService.validateUserByPassword(user);

      if (result) {
        response.cookie('access_token', result.token);
        return result;
      }
      throw new AuthenticationError(
        'Could not log-in with the provided credentials',
      );
    } catch (err) {
      throw err;
    }
  }
}

I can't seem to figure out why, as from my point of view, everything should be working.

I tried Fastify platform with Fastify cookie, and I am getting a similar error. I am expecting to set the cookie.

英文:

I Have a nestjs graphQL auth microservice and trying to set a http only cookie containing the token, and for some reason setting the cookie doesn't work, i get this error:

{
  &quot;errors&quot;: [
    {
      &quot;message&quot;: &quot;response.cookie is not a function&quot;,
      &quot;path&quot;: [
        &quot;login&quot;
      ],
      &quot;extensions&quot;: {
        &quot;code&quot;: &quot;INTERNAL_SERVER_ERROR&quot;,
        &quot;stacktrace&quot;: [
          &quot;GraphQLError: response.cookie is not a function&quot;,
          &quot;    at downstreamServiceError (/home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:872:12)&quot;,
          &quot;    at /home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:577:9&quot;,
          &quot;    at Array.map (&lt;anonymous&gt;)&quot;,
          &quot;    at sendOperation (/home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:576:38)&quot;,
          &quot;    at processTicksAndRejections (node:internal/process/task_queues:95:5)&quot;,
          &quot;    at /home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:450:41&quot;,
          &quot;    at executeNode (/home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:372:9)&quot;,
          &quot;    at /home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/executeQueryPlan.ts:195:27&quot;,
          &quot;    at /home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/gateway/src/index.ts:826:28&quot;,
          &quot;    at execute (/home/ghassen/Desktop/pfe/MyKlad Project/api-gateway/node_modules/@apollo/server/src/requestPipeline.ts:536:22)&quot;
        ],
        &quot;serviceName&quot;: &quot;users&quot;
      }
    }
  ],
  &quot;data&quot;: null
}

Here is main.ts

async function bootstrap() {
  const app: NestExpressApplication =
    await NestFactory.create&lt;NestExpressApplication&gt;(
      UsersModule,
      new ExpressAdapter(),
    );

  app.use(cookieParser());

  return app.listen(9009);
}

bootstrap();

and this is my auth resolver

@Resolver(&#39;Auth&#39;)
export class AuthResolver {
  constructor(private authService: AuthService) {}

  @Query(&#39;login&#39;)
  async login(
    @Res() response: Response,
    @Args(&#39;user&#39;) user: LoginUserInput,
  ): Promise&lt;LoginResult&gt; {
    // log(res.cookie(&#39;test&#39;, 33));

    try {
      const result = await this.authService.validateUserByPassword(user);

      if (result) {
        response.cookie(&#39;access_token&#39;, result.token);
        return result;
      }
      throw new AuthenticationError(
        &#39;Could not log-in with the provided credentials&#39;,
      );
    } catch (err) {
      throw err;
    }
  }

}

i can't seem to figure out why as for my point of view everything should be working.

I tried fastify platform, with fastify cookie and I am getting a similar error.
I am expecting to set the cookie

答案1

得分: 1

@Res() 不是GraphQL解析器的有效装饰器。您应该改用@Context()来获取上下文对象,然后从中提取res对象。

@Context() { res }@Context() ctx => ctx.res 应该可以解决问题。您可能需要修改您的GraphQlModule.forRoot()以包括context: ({ req, res }) => ({ req, res })

英文:

@Res() is not a valid decorator for GraphQL resolvers. You should instead use @Context() to get the context object and pull the res object from there.

@Context() { res } or @Context() ctx => ctx.res should do it. You may need to modify your GraphQlModule.forRoot() to include context: ({ req, res }) =&gt; ({ req, res })

huangapple
  • 本文由 发表于 2023年6月12日 10:42:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定