无法从上下文访问请求

时间:2018-11-17 11:55:01

标签: graphql apollo apollo-server koa2

我将Koa.js与Apollo Server的apollo-server-koa结合使用。

我已经调试了{ req },该值未定义。 我遵循了文档,但是仍然没有任何线索。 即使我访问req.headers.authorization并将其放在graphql gui的HTTP标头上,也是如此:

{
  "authorization": "bla"
}

该值仍为undefined

app.ts:

import cors from "@koa/cors";
import Koa from "koa";

import config from "./config/environtment";
import server from "./server";

const PORT: number = config.port;

async function bootstrap() {
  try {
    const app: Koa = new Koa();

    server.applyMiddleware({ app });

    app
      .use(cors())
      .listen(PORT, () =>
        console.log(
          `Server running on http://localhost:${PORT}${server.graphqlPath}`,
        ),
      );
  } catch (error) {
    console.error(error);
  }
}

bootstrap();

server.ts:

import { ApolloServer } from "apollo-server-koa";

import typeDefs from "./graphql/schema";
import resolvers from "./graphql/resolvers";
import context from "./graphql/context";

export default new ApolloServer({
  typeDefs,
  resolvers,
  context,
});

context.ts

export default ({ req }) => {
  console.log(req) // return undefined.
  return {
    test: "test",
  };
};

1 个答案:

答案 0 :(得分:1)

该文档特定于apollo-server,在后台使用apollo-server-express。我相信对于apollo-server-koa,选项将在带有ctx字段的对象中传递,该字段包含Koa Context。因此,以下方法应该起作用:

export default ({ ctx }) => {
  console.log(ctx.request)
  console.log(ctx.response)
  return {};
};