调用Squarespace API上传产品图片报错(无file文件),JavaScript代码如何修复?
问题
尝试使用Squarespace开发者API上传产品图片,官网示例采用cURL编写,自行编写的JavaScript代码如下:
const form = new FormData(); form.append("file", fs.createReadStream("./images/" + data._id + ".png")); const send_img = await fetch( "https://api.squarespace.com/1.0/commerce/products/" + img_id + "/images", { method: "POST", headers: { Authorization: "Bearer " + process.env.SQUARESPACE_API_KEY, "User-Agent": "MYUSERAGENT", "Content-Type": "multipart/form-data", }, body: form, } );
发送请求后收到错误,提示未检测到文件:
{ type: 'INVALID_REQUEST_ERROR', subtype: null, message: "Expected exactly one file part named 'file', but found none.", details: null, contextId: 'AWBREYTOOZEWWRIESHRE' }
解决方法
移除手动设置的
Content-Type头
使用fetch发送FormData时,运行环境会自动生成包含边界标识的multipart/form-data请求头,手动设置该头会破坏自动生成的结构,导致服务器无法解析文件。修改后的请求配置:const send_img = await fetch( "https://api.squarespace.com/1.0/commerce/products/" + img_id + "/images", { method: "POST", headers: { Authorization: "Bearer " + process.env.SQUARESPACE_API_KEY, "User-Agent": "MYUSERAGENT" // 移除Content-Type字段 }, body: form, } );验证文件路径与存在性
确保fs.createReadStream指向的文件真实存在,可提前添加检查逻辑:const filePath = `./images/${data._id}.png`; if (!fs.existsSync(filePath)) { throw new Error(`目标文件不存在:${filePath}`); } const form = new FormData(); form.append("file", fs.createReadStream(filePath));Node.js环境下使用
form-data库
原生FormData在Node.js环境中处理文件流可能存在兼容性问题,可安装form-data库构建表单:npm install form-data代码修改如下:
const FormData = require('form-data'); const form = new FormData(); form.append("file", fs.createReadStream(`./images/${data._id}.png`)); const send_img = await fetch( "https://api.squarespace.com/1.0/commerce/products/" + img_id + "/images", { method: "POST", headers: { Authorization: "Bearer " + process.env.SQUARESPACE_API_KEY, "User-Agent": "MYUSERAGENT", ...form.getHeaders() }, body: form, } );
内容的提问来源于stack exchange,提问作者RaptorRV
相关产品推荐
相关产品推荐

