JS发送Multipart POST请求遇Token错误及Insomnia请求定时执行问题
问题一:Token错误的排查与解决
核心错误点
- 手动指定Content-Type的boundary:你手动设置了
multipart/form-data的boundary值,但form-data库会自动生成匹配表单内容的boundary,手动指定的边界和实际表单的边界不匹配,导致后端无法正确解析表单数据,进而触发Token验证失败。 - httpsAgent放置位置错误:你把
agent放在了headers对象里,这是错误的——agent是fetch配置项的顶级属性,不属于HTTP请求头的一部分。 - 可能缺失User-Agent头:部分后端会校验请求的User-Agent,你注释掉了Insomnia的UA头,可能导致后端拒绝请求。
修正后的代码
import FormData from 'form-data'; import fetch from 'node-fetch'; import https from 'https'; // 可选:如果httpsAgent不生效,打开这行强制关闭SSL验证 // process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'; const form = new FormData(); form.append("...", "..."); form.append("...", "..."); form.append("...", "..."); form.append("...", "..."); // 绕过SSL验证的httpsAgent const httpsAgent = new https.Agent({ rejectUnauthorized: false, }); const options = { method: 'POST', // 移除手动的Content-Type,让form-data自动生成正确的boundary headers: { 'User-Agent': 'insomnia/2023.5.8', // 恢复Insomnia的UA头 }, agent: httpsAgent, // 将agent移到options顶级 body: form }; fetch('https://XXXXX', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err));
额外排查建议
- 检查表单字段名和值是否和Insomnia中完全一致,包括大小写、特殊字符。
- 用
console.log(form.getHeaders())打印form-data自动生成的请求头,确认和Insomnia中的请求头一致。
问题二:请求自动化执行方案
方案1:用setInterval实现固定间隔调用
适合简单的固定时间间隔需求,比如每30秒调用一次:
// 复用问题一中修正后的请求逻辑 import FormData from 'form-data'; import fetch from 'node-fetch'; import https from 'https'; const httpsAgent = new https.Agent({ rejectUnauthorized: false }); async function sendRequest() { const form = new FormData(); form.append("...", "..."); // 其他表单字段 try { const response = await fetch('https://XXXXX', { method: 'POST', headers: { 'User-Agent': 'insomnia/2023.5.8' }, agent: httpsAgent, body: form }); const result = await response.json(); console.log(new Date().toLocaleString(), '请求结果:', result); } catch (err) { console.error(new Date().toLocaleString(), '请求失败:', err); } } // 首次立即执行,之后每XXX秒执行一次 sendRequest(); const interval = 30000; // 30秒,单位毫秒 setInterval(sendRequest, interval);
方案2:用node-schedule实现复杂定时规则
如果需要更灵活的定时(比如每天凌晨2点执行),可以安装node-schedule库:
npm install node-schedule
示例代码:
import schedule from 'node-schedule'; // 复用sendRequest函数(同方案1) // 每天凌晨2点执行 schedule.scheduleJob('0 0 2 * * *', sendRequest); // 或者每30秒执行一次 schedule.scheduleJob('*/30 * * * * *', sendRequest);
方案3:系统级定时任务
不需要持续运行Node脚本的话,可以用系统自带的定时工具:
- Linux/macOS:使用
crontab,编辑定时任务:
添加一行(每30秒执行一次脚本):crontab -e*/30 * * * * cd /path/to/your/script && node your-script.js >> log.txt 2>&1 - Windows:打开「任务计划程序」,创建基本任务,设置触发频率和执行的Node脚本路径。
方案4:用PM2守护进程
如果需要脚本持续运行且异常重启,可以用PM2:
npm install pm2 -g pm2 start your-script.js --name "auto-request" # 查看日志 pm2 logs auto-request # 设置开机自启 pm2 startup pm2 save
内容的提问来源于stack exchange,提问作者Benny
相关产品推荐
相关产品推荐

