Chrome扩展无法访问Shopify自定义应用API求助
问题:Chrome扩展调用Shopify API失败,报错"Required parameter missing or invalid"
我正在开发一款Chrome扩展,不管用基础认证还是X-Shopify-Access-Token请求头,都没法访问Shopify API。已经确认访问权限范围(access scopes)和Token值都是对的,但还是收到报错。
我的代码实现
background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.contentScriptQuery == "query") { var url = "https://<store>.myshopify.com/admin/api/2024-07/graphql.json"; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Shopify-Access-Token': 'value' }, body: JSON.stringify(`{ shop { name } }`) }) .then(response => response.json()) .then(r => { sendResponse(r); }).catch(error => sendResponse(error)); return true; });
content.js
function testFetch() { chrome.runtime.sendMessage({ contentScriptQuery: "query", }, response => { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError.message); } else { console.log('response: ', response); } }); }
报错信息
response: errors {query: 'Required parameter missing or invalid'} [[Prototype]] Object
解决方案
问题出在GraphQL请求的body格式上:你现在用JSON.stringify直接包裹了GraphQL查询字符串,导致最终发送的是一个字符串的JSON序列化结果,而Shopify GraphQL API要求的是一个包含query字段的JSON对象。
修改background.js中fetch的body部分即可:
body: JSON.stringify({ query: `{ shop { name } }` })
额外需要检查的点:
- 确认代码中的
<store>已经替换成你的实际店铺域名 - 确保
X-Shopify-Access-Token的value是有效的管理员权限Token(不是店铺前端的API密钥) - 检查Chrome扩展的manifest.json中,是否在
permissions数组里添加了对目标Shopify域名的访问权限,比如:"https://<store>.myshopify.com/*"
内容的提问来源于stack exchange,提问作者Sean
相关产品推荐
相关产品推荐

