如何让基本的 Shopify GraphQL Admin API 使用 nodeJS?

How to get basic Shopify GraphQL Admin API working with nodeJS?

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

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

我在我的商店中启用了一个“私人应用程序”,并为所有 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 好像有误。您发送 body 的方式导致 {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

的不错的参考