首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

express-graphql -如何将res对象传递给上下文中的自定义函数?

express-graphql 是一个用于构建 GraphQL 服务器的库,它允许你将 Express 应用程序与 GraphQL 结合使用。在 GraphQL 中,上下文(context)是一个非常重要的概念,它可以在解析器(resolver)之间共享数据。

要将 res 对象传递给上下文中的自定义函数,你需要在创建 GraphQL 服务器时定义一个上下文函数,并在该函数中包含 res 对象。以下是一个示例代码:

代码语言:txt
复制
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

// 创建一个简单的 Express 应用程序
const app = express();

// 定义 GraphQL schema
const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// 定义根解析器
const root = {
  hello: () => 'Hello world!'
};

// 定义上下文函数,将 res 对象传递给上下文
const context = ({ req, res }) => ({
  res,
  // 你可以在这里添加其他需要传递到上下文的数据
});

// 创建 GraphQL 服务器
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  context: context,
  graphiql: true // 启用 GraphiQL 工具
}));

// 启动服务器
app.listen(4000, () => {
  console.log('Running a GraphQL API server at http://localhost:4000/graphql');
});

在这个示例中,我们定义了一个上下文函数 context,它接收 reqres 对象,并将 res 对象包含在返回的上下文对象中。这样,在解析器中,你就可以通过上下文访问 res 对象。

例如,你可以在解析器中使用 context.res 来设置响应头或发送响应:

代码语言:txt
复制
const root = {
  hello: (args, context) => {
    context.res.setHeader('X-Custom-Header', 'CustomValue');
    return 'Hello world!';
  }
};

参考链接

通过这种方式,你可以将 res 对象传递给上下文中的自定义函数,并在解析器中使用它来处理响应。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券