gpt4 book ai didi

node.js - 如何获得与 nodeJS 一起使用的基本 Shopify GraphQL Admin API?

转载 作者:行者123 更新时间:2023-12-05 03:44:18 70 4
gpt4 key购买 nike

昨天我度过了一个非常沮丧的夜晚,试图让基本的 Shopify GraphQL Admin API 示例与 nodeJS 一起工作。原始 Shopify 示例代码为 here .

问题是我的代码返回状态 400 - 错误请求。

我在我的商店中启用了一个“私有(private)应用程序”,并启用了所有具有读取权限的 API。我从 Shopify 中小心地复制了 apiKey、accessToken 和商店名称。

谁能指出我的代码是否有问题?非常感谢。

代码:

import fetch from 'node-fetch';

const apiKey = 'xxxx';
const accessToken = 'yyyy';
const store = 'zzzz';
const hostName = store + '.myshopify.com';
const apiVersion = '2021-01';
const apiLocation = '/admin/api/';

const rootUrl = 'https://' + apiKey + ':' + accessToken + '@' + hostName + apiLocation + apiVersion + '/';

const shopGraphQl = 'https://' + hostName + apiLocation + apiVersion + '/graphql.json';
//const shopGraphQl2 = rootUrl + 'graphql.json';
//const urlTest = rootUrl + 'orders.json';

const url = shopGraphQl;

const body = {
query: `{
shop {
name
}
}`
};

fetch (
url,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Shopify-Access-Token" : accessToken
},
body: JSON.stringify({
body
})
}
)
.then(res => {
console.log('status = ' + res.status + ' , ' + res.statusText);
})
.then(json => {
console.log("data returned:\n", json);
})
.catch(err => console.error(err));;

最佳答案

看起来您发送的正文不正确。您发送正文的方式导致 {body: { query: { shop { name } } }

代替:

body: JSON.stringify({body})

将其更改为:

body: JSON.stringify(body)

从fetch接收数据

您已经注意到您的 console.log 语句 console.log("data returned:\n", json); 正在返回 undefined。这样做的原因是您需要从响应中提取 json (res.json())。

return fetch (
url,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Shopify-Access-Token" : accessToken
},
body: JSON.stringify(body)
}
)
.then(res => {
console.log(`status = ${res.status}, ${res.statusText}`);
return res.json();
})
.then(json => {
console.log("data returned:\n", json);
})
.catch(err => console.error(err));;

这是关于使用 fetch 的不错引用

关于node.js - 如何获得与 nodeJS 一起使用的基本 Shopify GraphQL Admin API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66514765/

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