express - 无法读取未定义的属性 'context' - GraphQL

标签 express graphql typegraphql

我正在使用 Typescript、Express、TypeORM、GraphQL 和 TypeGraphQL 来构建一个允许用户登录的小应用程序。

但是,当我点击我的测试查询时 bye在 GraphQL 操场上,我得到:

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");
  }
...

用户解析器
  @Query(() => String)
  @UseMiddleware(isAuth)
  bye(@Ctx() { payload }: MyContext) {
    console.log(payload);
    return `your user id is: ${payload!.userId}`;
  }

我不知道为什么 context在文件 isAuth.js 中未定义

最佳答案

解决感谢:https://github.com/MichalLytek/type-graphql/issues/433

1) 进入 ./tsconfig.json
2) 更改 "target": "es5""target": "es6"

关于express - 无法读取未定义的属性 'context' - GraphQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61291222/

相关文章:

javascript - req.body 为空 Express js

node.js - Socket.io如何检查客户端的cookie数据?

mongodb - Mongoose 不会删除嵌入的文档

graphql - 为什么GraphQL查询返回null?

typescript - 使用 webpack 和 babel-loader 进行转译时,TypeGraphQL @Arg 装饰器失败并出现解析器错误

javascript - 如何在 cpanel 托管上部署 Next js 应用程序

graphql - ApolloBoost 被初始化为不支持的选项 :

javascript - 如何在 React 中映射一个 prop,它是一个对象数组

graphql - 可选参数 - Mutation - TypeGraphQL

postgresql - 将新值添加到现有 ENUM Type In prisma