gpt4 book ai didi

GraphQL:无法读取 Apollo 客户端中的响应 header

转载 作者:行者123 更新时间:2023-12-04 21:30:03 27 4
gpt4 key购买 nike

我想用 Apollo Client 读取响应头,但我不能。

我正在使用 Apollo 服务器和 Apollo 客户端进行 GraphQL API 通信,并且我想来回发送 header 。我已经设置了客户端,以便它发送一个 x-client-version header ,并且我已经将服务器设置为有时也使用相同的 header 进行回复。

问题是,当我尝试使用 Apollo 客户端读取 x-client-version header (或任何真正的 header )时,我得到未定义。我根据我在网上找到的示例甚至 YouTube 演练在下面设置了一些 Afterware:

const clientVersionAfterware = new ApolloLink((operation, forward) =>
forward(operation).map(response => {
const {
response: { headers },
} = operation.getContext();
console.log(headers);
if (headers) {
const token = headers.get("x-client-version");
console.log(token);
if (token) {
localStorage.setItem("clientVersion", token);
}
}

return response;
}),
);

将其附加到链接链:
    const httpLink = handleErrors.concat(
clientVersionAfterware.concat(new HttpLink(linkOptions)),
);
const batchHttpLink = handleErrors.concat(
clientVersionAfterware.concat(
new BatchHttpLink({ ...linkOptions, batchInterval: 10 }),
),
);

最终连接 ApolloClient 构造函数中的链接:
new ApolloClient({
link: split(
({ operationName = "" }) => operationName.startsWith("findOrCreate"),
httpLink,
batchHttpLink,
),
cache,
...opts,
});

我听说标题对象是空白的,但标题仍然可以读取,但根据我的经验,这绝对不是真的。我可以看到服务器确实返回了 x-client-version我希望阅读的标题:

Chrome Response Headers

我认为升级我的软件包可能会有所帮助,但他们没有。我正在使用的版本:
"apollo-cache-inmemory": "^1.5.1",
"apollo-client": "^2.5.1",
"apollo-link-batch-http": "^1.2.4",
"apollo-link-error": "^1.1.2",
"apollo-link-http": "^1.5.11",

有什么我想念的吗?提前致谢!

最佳答案

我想到了。

结果证明更新 apollo-client 是不够的。我升级了以下包,现在填充了 headers 对象:

"apollo-link-batch-http": "^1.2.9",
"apollo-link-error": "^1.1.8",
"apollo-link-http": "^1.5.12",

我确定您不需要更新 apollo-link-error,但其他两个应该就足够了(尤其是 apollo-link-http)。

关于GraphQL:无法读取 Apollo 客户端中的响应 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54990173/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com