我正在使用Typescript,Express,TypeORM,GraphQL和TypeGraphQL来构建一个允许用户登录的小型应用程序。
但是,当我在GraphQL操场上点击测试查询bye
时,我得到:
Cannot read property 'context' of undefined
"TypeError: Cannot read property 'context' of undefined",
" at new exports.isAuth // isAuth is a JS file I wrote
MyContext.js
import { Request, Response } from "express";
export interface MyContext {
req: Request;
res: Response;
payload?: { userId: string };
}
isAuth.js
import { MiddlewareFn } from "type-graphql";
import { verify } from "jsonwebtoken";
import { MyContext } from "./MyContext";
export const isAuth: MiddlewareFn<MyContext> = ({ context }, next) => {
const authorization = context.req.headers["authorization"];
if (!authorization) {
throw new Error("not authorized");
}
...
UserResolver
@Query(() => String)
@UseMiddleware(isAuth)
bye(@Ctx() { payload }: MyContext) {
console.log(payload);
return `your user id is: ${payload!.userId}`;
}
我不确定为什么在文件context
中未定义isAuth.js
答案 0 :(得分:1)
已解决:https://github.com/MichalLytek/type-graphql/issues/433
1)进入./tsconfig.json
2)将"target": "es5"
更改为"target": "es6"