使用Got向Shopify发送添加购物车POST请求时出现400错误的排查与解决指导请求
400 Bad Request when using Got library to send POST request to Shopify cart/add.js
问题描述
我尝试使用Got库向Shopify站点发送POST请求实现添加购物车功能,参考了Shopify AJAX API的结构,但发送请求后一直返回400 Bad Request错误,找不到问题所在。以下是我的代码实现:
const main = async () => { const res = await got.get('https://barstoolkicks.com/products.json?limit=250&page=1&order=updated_at').json(); const productId = res.products[7].id const variantId = res.products[7].variants[0].id // ATC let data = { 'items': [{ // 'form_type': 'product', // 'utf8': '✓', 'id': variantId, 'quantity': 1 }] } const atc = await got.post('https://barstoolkicks.com/cart/add.js', { headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25' }, data: JSON.stringify(data), }) .then(res => console.log(res.data)) .catch(err => console.error(err)); } main();
解决方案
我之前也碰到过类似的问题,Shopify的cart/add.js接口对请求格式和会话信息有不少细节要求,你可以试试以下几个调整:
1. 改用application/x-www-form-urlencoded格式发送请求
虽然Shopify文档提到支持JSON格式,但很多Shopify站点实际更兼容表单编码格式。这是最容易触发400错误的点,优先调整这个试试。
2. 带上会话Cookie
Shopify需要通过Cookie识别用户会话来关联购物车,没有Cookie的请求大概率会被拒绝。你可以先请求站点首页获取会话Cookie,再在添加购物车的请求中带上。
3. 打印详细错误信息
Shopify的400错误通常会返回具体的错误原因(比如variant无效、库存不足等),在catch块里打印err.response.data能帮你快速定位问题,而不是只看错误状态码。
修改后的代码示例:
const main = async () => { const res = await got.get('https://barstoolkicks.com/products.json?limit=250&page=1&order=updated_at').json(); const variantId = res.products[7].variants[0].id // 先获取站点会话Cookie const initialPageRes = await got.get('https://barstoolkicks.com'); const sessionCookies = initialPageRes.headers['set-cookie']; // 构建表单格式的数据 const formData = new URLSearchParams(); formData.append('id', variantId); formData.append('quantity', 1); try { const atcResponse = await got.post('https://barstoolkicks.com/cart/add.js', { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25', 'Cookie': sessionCookies.join('; ') }, body: formData.toString(), }); console.log('添加购物车成功:', atcResponse.data); } catch (err) { // 打印Shopify返回的具体错误信息 console.error('添加失败,错误详情:', err.response?.data || err.message); } } main();
如果还是想用JSON格式请求,确保请求头Content-Type正确设置为application/json,同时确认该Shopify站点确实支持JSON格式的cart/add.js请求(部分主题可能关闭了这个支持)。
内容的提问来源于stack exchange,提问作者Ryan Tang
相关产品推荐
相关产品推荐

