Nest/Graphql 中如何取req及header里面的内容

Nest/Graphql 中如何取req及header里面的内容

十月 31, 2019

Nest/Graphql 中如何取req及header里面的内容

这两天用nest写graphql的时候,需要取header里面的内容。可是翻了官方文档,没找到。
搜了很久才找到答案,特此记录下,并希望能帮助到大家。
在nest/graphql中是不能直接取得req及header的,它用的是context,看起来和koa有点像,那如何使用呢,直接贴代码:

1
2
3
4
5
6
7
8
GraphQLModule.forRoot({
debug: false,
playground: true,
autoSchemaFile: './schema.gql',
path: '/api/graphql',
context: ({ req }) => req, // 必须的
installSubscriptionHandlers: true,
}));

上面的context是必须的,不然在后面的接口里,就算用了context,取值也不对。

第二步,在resolver中:

1
2
3
4
import { Context } from '@nestjs/graphql';
async ctxExample(@Context() ctx): Promise<xxx> {
console.log(ctx) //这里取的就是req内容,下来和平时怎么写的基本一致
}

完美收工~!