我正在开发一个 chrome 扩展,它将现有的 GraphQL 查询发送到站点。
使用 Apollo chrome 扩展进行测试,我成功地正确发送了我的查询。
但是当我通过脚本执行此操作时,我似乎收到身份验证错误:“用户不是工作区管理员”。
我的查询是从 chrome.scripting.executeScript 中调用的,并且仅限于:
const doSomething = async () => {
const query = JSON.stringify({
query: `MY QUERY`
});
const response = await fetch(TARGET_URL, {
headers: { 'content-type': 'application/json' },
method: 'POST',
body: query,
});
const responseJson = await response.json();
console.log(responseJson);
return responseJson.data;
};
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: doSomething
}, (result) => {
console.log(result[0].result);
});
});
const responseJson = await response.json();
console.log(responseJson);
我认为我缺少一个身份验证步骤,但我不明白为什么我的 Apollo 扩展和我的有差异。
Apollo 如何设法执行其请求?我如何更新我的脚本以实现类似的目标?
正如 @phry 提到的,我们通过 Chrome 扩展检测到的 Apollo 客户端实例发送请求(无论设置为
window.__APOLLO_CLIENT__
)。这意味着请求也将通过您的链接链,其中可能包括一些将身份验证标头附加到请求的逻辑。
查看您的代码示例,我没有看到您的
fetch
请求中设置了任何其他标头信息,因此该请求可能不会以相同的方式进行身份验证。如果您想检查应用程序的 Apollo 客户端实例发送的内容,您可以覆盖 fetch
上的 HttpLink
函数 并记录请求。
createHttpLink({
fetch: (uri, options) => {
console.log(uri, options)
return window.fetch(uri, options);
}
})
// or if you use the constructor to create the link
new HttpLink({
fetch: (uri, options) => {
console.log(uri, options)
return window.fetch(uri, options);
}
})
只需确保脚本中的
fetch
函数包含您在此处看到的任何所需的身份验证标头。希望这有帮助!