使用Gorgias API上传文件遇201无返回数据问题求助
排查Gorgias文件上传API返回201但无数据的问题
核心问题分析
返回201状态码但无数据,说明服务端接收了请求但未正确处理文件,大概率是FormData的格式不符合API要求,结合Gorgias上传规则,以下是具体排查和修复方案:
修复方案
1. 给FormData的文件字段添加文件名
Gorgias的上传API要求file字段必须包含文件名,你当前只传入了可读流,服务端无法识别文件类型和名称,导致上传无效。
修改form.append的代码:
// 先引入path模块 import path from 'path'; // 替换原有的append语句 form.append('file', fs.createReadStream(filePath), { filename: path.basename(filePath) // 自动提取路径中的文件名 });
2. 修正异步文件检查的时序问题
你用了fs.access的回调版本,这是异步操作,会在FormData创建后才执行,虽然不直接影响上传,但建议改成异步同步写法,避免逻辑混乱:
// 替换原有的文件检查代码 try { await fs.promises.access(filePath, fs.constants.F_OK | fs.constants.R_OK); console.log('文件存在且可读'); } catch (err) { console.error('文件异常:', err); throw err; // 直接抛出错误终止上传流程 }
3. 优化Axios的请求配置
Node.js环境下,Axios处理大文件流时需要放宽内容长度限制,同时确保请求头正确合并:
const response = await axios({ method: 'post', url: 'https://my-company.gorgias.com/api/upload?type=attachment', data: form, headers: { 'Authorization': 'Basic XXXX==', ...form.getHeaders() }, maxContentLength: Infinity, maxBodyLength: Infinity // 取消内容长度限制 });
4. 验证权限与端点正确性
- 确认Basic Auth凭证
XXXX==是正确的,该账号拥有文件上传权限 - 检查端点URL是否符合格式:
https://{你的域名}.gorgias.com/api/upload,type=attachment参数是否符合API要求
完整修复后的代码
import fs from 'fs'; import path from 'path'; import axios from 'axios'; import FormData from 'form-data'; export const uploadFileFromBase64 = async (): Promise<any> => { const filePath = '/Users/rafaelpolonio/Documents/51c1076a502ed528e6696c72b5fecfef-silhueta-de-transporte-de-skate.png'; // 检查文件状态 try { await fs.promises.access(filePath, fs.constants.F_OK | fs.constants.R_OK); console.log('文件存在且可读'); } catch (err) { console.error('文件异常:', err); throw err; } // 构建FormData const form = new FormData(); form.append('file', fs.createReadStream(filePath), { filename: path.basename(filePath) }); // 发送上传请求 try { const response = await axios({ method: 'post', url: 'https://my-company.gorgias.com/api/upload?type=attachment', data: form, headers: { 'Authorization': 'Basic XXXX==', ...form.getHeaders() }, maxContentLength: Infinity, maxBodyLength: Infinity }); console.log('上传成功:', response.data); return response.data; } catch (err) { console.error('上传失败:', err.response?.data || err.message); throw err; } };
内容的提问来源于stack exchange,提问作者polonio
相关产品推荐
相关产品推荐

