You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Node.js实现curl调用的multipart/mixed类型API请求?

Node.js实现等价于指定curl的API调用

原可正常工作的curl命令

curl -k --user "un:$PASSWORD" -X POST -H "Content-type: multipart/mixed" -F "blob=@binaryfile" -F 'metadata={"prop1":"v1","prop2":"v2"};type=application/json' https://<host>/api/v2.0/entity

你当前尝试的axios代码

formData.append('blob', fs.createReadStream(binaryfile))
formData.append('metadata', fs.createReadStream(jsonfile))
const config = {
    method: 'POST',
    url: 'https://<host>/api/v2.0/entity',
    headers: {
        'Content-Type': 'multipart/mixed',
        'Accept': 'application/json'
    },
    data: formData
}

return await axios(config).then(function (response) {
    return response.data
}).catch(error => {
    return error
})

问题分析与修正方案

你的代码存在几个关键问题,对应curl的特性没有正确实现,修正如下:

  • 缺少基础认证:curl的--user "un:$PASSWORD"对应axios的auth配置项,需要添加账号密码验证
  • metadata参数处理错误:curl里是直接传递JSON字符串并指定type=application/json,不需要读取文件流,直接传入JSON内容并设置对应Content-Type
  • 不需要手动设置Content-Type:axios会自动根据FormData生成正确的multipart/mixed类型及边界标识,手动设置反而可能导致错误
  • 忽略SSL证书验证:curl的-k参数对应axios的httpsAgent配置,需要禁用证书校验

修正后的完整代码

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const https = require('https');

async function callApi(binaryfile, password) {
    const formData = new FormData();
    // 添加二进制文件流,和curl的blob=@binaryfile一致
    formData.append('blob', fs.createReadStream(binaryfile));
    // 添加metadata参数,直接传入JSON字符串并指定Content-Type,对应curl的metadata配置
    formData.append('metadata', JSON.stringify({"prop1":"v1","prop2":"v2"}), {
        contentType: 'application/json'
    });

    const config = {
        method: 'POST',
        url: 'https://<host>/api/v2.0/entity',
        headers: {
            // 继承FormData的headers,自动生成正确的multipart头部
            ...formData.getHeaders(),
            'Accept': 'application/json'
        },
        auth: {
            username: 'un',
            password: password // 对应curl的$PASSWORD变量
        },
        // 对应curl的-k参数,忽略SSL证书验证
        httpsAgent: new https.Agent({
            rejectUnauthorized: false
        }),
        data: formData
    };

    try {
        const response = await axios(config);
        return response.data;
    } catch (error) {
        return error;
    }
}

额外说明

如果你的metadata内容确实来自JSON文件,可以先读取文件内容再传入,而不是用文件流:

const metaContent = fs.readFileSync(jsonfile, 'utf8');
formData.append('metadata', metaContent, { contentType: 'application/json' });

确保已经安装所需依赖:npm install axios form-data

内容的提问来源于stack exchange,提问作者Anil Samuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 02:22:15