Apollo GraphQL iOS:请求报错,如何移除请求体中的operationName?
Apollo GraphQL iOS移除请求体中operationName的方法
可以移除请求体里的operationName,具体通过自定义拦截器修改请求内容即可实现:
自定义拦截器修改请求体
创建一个实现ApolloInterceptor协议的类,在拦截方法中清空请求体的operationName字段:class RemoveOperationNameInterceptor: ApolloInterceptor { func interceptAsync<Operation>( chain: RequestChain, request: HTTPRequest<Operation>, response: HTTPResponse<Operation>?, completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void ) where Operation : GraphQLOperation { var modifiedRequest = request modifiedRequest.requestBody?.operationName = nil chain.proceedAsync(request: modifiedRequest, response: response, completion: completion) } }将拦截器加入客户端拦截链
初始化Apollo客户端时,把自定义拦截器添加到拦截器列表中,确保放在NetworkFetchInterceptor之前:let endpointURL = URL(string: "你的GraphQL接口地址")! let interceptorProvider = DefaultInterceptorProvider(client: ApolloClient()) let client = ApolloClient( networkTransport: RequestChainNetworkTransport( interceptorProvider: interceptorProvider, endpointURL: endpointURL, interceptors: [RemoveOperationNameInterceptor(), NetworkFetchInterceptor()] ) )
注意事项
- 确认后端支持不带
operationName的请求,根据你的错误提示,后端明确禁止了当前使用的operationName,移除后应该能解决「request is not valid」的问题。 - 若使用Apollo iOS新版本,部分API可能有变动,核心逻辑仍是通过拦截器修改请求体,可根据实际版本调整代码。
内容的提问来源于stack exchange,提问作者psdevss
相关产品推荐
相关产品推荐

