You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Swift中Apollo GraphQL请求添加Header始终失败问题求助

Troubleshooting Apollo GraphQL couldNotParseToLegacyJSON Error with Shopify API

Hey there, let’s break down why you’re hitting that frustrating LegacyParsingError.couldNotParseToLegacyJSON error and fix it step by step. This issue almost always stems from misconfigured interceptors, malformed response data, or missing required headers. Here’s what to check:

1. Fix Your Interceptor Order

Apollo’s interceptors run in sequence, and the order matters a lot. Your current setup has AutomaticPersistedQueryInterceptor placed after the parsing step (which defeats its purpose—it needs to modify the request before it’s sent to the server). Also, your response interceptor is unnecessarily modifying request headers after the server has already received the request.

Here’s the corrected interceptor order:

func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {
    return [
        MaxRetryInterceptor(),
        LegacyCacheReadInterceptor(store: self.store),
        AutomaticPersistedQueryInterceptor(), // Move this BEFORE network fetch
        RequestOrderDetailInterceptor(), // Add headers right before sending the request
        NetworkFetchInterceptor(client: self.client),
        ResponseCodeInterceptor(), // Check HTTP status codes first
        ResponseOrderDetailInterceptor(), // Log response AFTER status check
        LegacyParsingInterceptor(cacheKeyForObject: self.store.cacheKeyForObject),
        LegacyCacheWriteInterceptor(store: self.store)
    ]
}

2. Remove Unnecessary Header Addition in Response Interceptor

Your ResponseOrderDetailInterceptor is adding the X-Shopify-Access-Token again, but this happens after the server has already processed the request—this does nothing and just adds noise. Remove that line entirely:

class ResponseOrderDetailInterceptor: ApolloInterceptor {
    enum ResponseLoggingError: Error {
        case notYetReceived
    }
    
    func interceptAsync<Operation: GraphQLOperation>(
        chain: RequestChain,
        request: HTTPRequest<Operation>,
        response: HTTPResponse<Operation>?,
        completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
            defer {
                chain.proceedAsync(request: request, response: response, completion: completion)
            }
            
            guard let receivedResponse = response else {
                chain.handleErrorAsync(ResponseLoggingError.notYetReceived, request: request, response: response, completion: completion)
                return
            }
            
            print("HTTP Response: \(receivedResponse.httpResponse)")
            if let stringData = String(bytes: receivedResponse.rawData, encoding: .utf8) {
                print("Data: \(stringData)")
            } else {
                print("Could not convert data to string!")
            }
        }
}

3. Add Required Content-Type Header

Shopify’s GraphQL API explicitly expects requests to have Content-Type: application/json. While Apollo usually adds this automatically, it’s safe to explicitly set it in your request interceptor to avoid any gaps:

class RequestOrderDetailInterceptor: ApolloInterceptor {
    func interceptAsync<Operation: GraphQLOperation>(
        chain: RequestChain,
        request: HTTPRequest<Operation>,
        response: HTTPResponse<Operation>?,
        completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
            request.addHeader(name: "X-Shopify-Access-Token", value: "MyToken")
            request.addHeader(name: "Content-Type", value: "application/json") // Add this line
            print( "Outgoing request: \(request)")
            chain.proceedAsync(request: request, response: response, completion: completion)
        }
}

4. Verify the Raw Response Data

Look closely at the output from your ResponseOrderDetailInterceptor—specifically the Data: \(stringData) printout. If Shopify is returning an HTML page (like a 401 unauthorized error page) instead of JSON, that’s why the parser is failing. This usually means:

  • Your X-Shopify-Access-Token is invalid or has insufficient permissions
  • The API version (2021-04) is deprecated (Shopify retires old versions after 12 months—consider updating to a newer version like 2024-04)
  • The order ID you’re querying is invalid or doesn’t belong to the store associated with your token

5. Double-Check Your GraphQL Query

Ensure your OrderDetailsByIdQuery is correctly structured for the Shopify API. If the query has syntax errors, Shopify might return an error response that’s not properly formatted for Apollo’s legacy parser.

After making these changes, run your getOrderDetails() function again. If you still see the error, share the raw response data from your logging interceptor—that will help pinpoint exactly what’s coming back from Shopify.

内容的提问来源于stack exchange,提问作者Princess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:42:27