如何在express-graphql执行端点前运行函数并返回GraphQL错误?
在express-graphql中实现请求前的GraphQL层面验证
- 利用
graphqlHTTP的请求处理函数实现前置验证
express-graphql的graphqlHTTP支持传入一个动态配置函数,这个函数会在每次GraphQL请求处理前执行,你可以在这里完成JWT验证逻辑,并抛出标准的GraphQLError,错误会自动被处理器捕获并放入返回结果的errors数组中。
示例代码:
const { graphqlHTTP } = require('express-graphql'); const { GraphQLError } = require('graphql'); const { verifyToken } = require('./your-auth-utils'); // 你的JWT验证工具 app.use('/graphql', graphqlHTTP((req) => { // 从请求头提取JWT令牌 const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { throw new GraphQLError('请提供有效的Bearer令牌', { extensions: { code: 'UNAUTHENTICATED', }, }); } const token = authHeader.split(' ')[1]; let authenticatedUser; try { authenticatedUser = verifyToken(token); } catch (error) { throw new GraphQLError('令牌无效或已过期', { extensions: { code: 'UNAUTHENTICATED', }, }); } // 返回GraphQL配置,将验证后的用户信息传入context供resolvers使用 return { schema: yourGraphQLSchema, context: { user: authenticatedUser }, graphiql: process.env.NODE_ENV === 'development', }; }));
为什么这种方式符合需求
这种方式抛出的是GraphQL规范定义的错误,会被包含在响应体的errors数组中,不会触发HTTP状态码错误。客户端可以统一处理GraphQL响应的data和errors字段,保持API体验的一致性。注意事项
必须抛出graphql包提供的GraphQLError,而非普通的Error,这样才能被express-graphql正确识别并格式化到响应的errors数组里。
内容的提问来源于stack exchange,提问作者d512
相关产品推荐
相关产品推荐

