javascript - 通过调用 shopify api 创建新产品
问题描述
我正在尝试通过调用 shopify 产品 api (/admin/api/2020-01/products.json) 来创建新产品。我正在尝试使用“https”模块来实现这一点。下面是示例代码
const url1 = 'https://{api_token}@tuscstore.myshopify.com/admin/api/2020-01/products.json';
var obj = {
"product":[
{
"title": "Saturn",
"body_html": "<p>The epitome of elegance</p>",
"vendor": "Soltions inc",
"product_type": "Planets",
"handle": "saturn",
"tags": "",
"images": [
{
"src": "https://solarsystem.nasa.gov/system/stellar_items/image_files/38_saturn_1600x900.jpg"
}
]
}
]
};
const https = require('https');
var data = JSON.stringify(obj)
const options = new URL(url1);
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
/* res.on('data', (d) => {
process.stdout.write(d);
}); */
});
req.on('error', (e) => {
console.error(e);
});
req.write(data);
req.end();
const Index = () => (
<div>
<p>Sample app using React and Next.js</p>
</div>
);
export default Index;
我面临2个问题,
- 当我执行“process.stdout.write(d)”时,我收到无法读取属性“write”未定义。
- 如果我像在上面的代码中所做的那样将其注释掉,我不会收到错误消息。
在任何一种情况下,我都将状态码设为 200,而不是 201,根据 shopify 的文档,我应该收到 201。
有人可以帮我解决问题吗?
编辑:使用 Post,我得到一个类型错误
const https = require('https');
var data = JSON.stringify(obj)
var options = {
hostname: 'https://{apikey:password}@tuscstore.myshopify.com/admin/api/2020-01',
path: '/products.json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
/*'Content-Length': data.length*/
'Authorization' : 'API_TOKEN'
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
});
req.on('error', (e) => {
console.error(e);
});
req.write(data);
req.end();
TypeError:无法在“Window”上执行“fetch”:无法从https://[https:// {APIKEY:PWD}@tuscstore.myshopify.com/admin/api/2020-01]/products 解析 URL。 json
解决方案
您创建了一个新产品,您必须发出 http POST 请求,现在您发出 http GET 请求,您应该options
像这样更新:
const options = {
hostname: 'https://apikey:password@<@store_url>/admin/api/2020-01', // your host name
path: '/shop.json', // your end point
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization' : 'YOUR_API_TOKEN'
}
}
或者你可以使用这个包来解决你所有的问题https://www.npmjs.com/package/shopify-api-node
推荐阅读
- keyboard - 在 BIOS 中重新映射键盘
- python - 在为新列分配新值时如何根据开始和结束值列表循环索引
- ios - 如何将控制台打印语句保存到 Xcode 中的文本文件?
- reactjs - 如何在模糊上测试 formik yup 验证错误?
- r - 如何将多个分类变量重新组合成一个新变量
- javascript - Jest Test Visual Studio 代码调试器抛出“错误没有这样的文件”异常
- opencart - 代码更改 - 我在网站上没有看到
- python - 如何从 Python 中的字符串中提取整数或浮点值?
- reactjs - 静态 Web 应用程序上的 Web 推送通知
- arrays - Bash:不能附加到本地数组