axios 多部分请求失败

axios multipart request failing

我正在尝试发送 post 使用服务将 doc 转换为 pdf 的请求。该服务与 postman 一起工作正常,您可以将文档发送到端点,它 return 给我 pdf,很好。

但是我无法从我的 nodejs 服务器发出请求,我正在使用 axios 发出请求并且它失败了,这是错误:

{"time":"2019-09-24T14:39:46.89404124Z","id":"","remote_ip":"000.00.000.00","host":"pdf-doc-convert.example","method":"POST","uri":"/convert/office","user_agent":"axios/0.19.0","status":500,"error":"getting multipart form: no multipart boundary param in Content-Type","latency":221460,"latency_human":"221.46µs","bytes_in":0,"bytes_out":36}

这是服务文档,是一个带有 multipart/form-data 请求的简单 post(带有 curl 示例):

https://thecodingmachine.github.io/gotenberg/#office

这是我对 axios 的要求:

async function request() {
    const endpoint =
          "http://pdf-doc-convert.example/convert/office";
    const data = new FormData();
    data.append('files', fs.createReadStream("my/file/path/example.docx"));
    const config = {
      headers: {
        "content-type": "multipart/form-data"
      }
    };
    const pdf = await axios.post(endpoint, data, config);
}

我该如何提出请求?

也许调试此问题的最快方法是使用 Postman Intercept 拦截您使用 Axios 请求发出的调用,并将 cURL 请求信息从有效的请求信息与无效的请求信息进行比较。这可能是 headers 问题或文件编码问题。

我以前遇到过类似的事情,这可能与 formData headers 有关,需要在 Axios 中进行额外配置,如下所述:https://github.com/axios/axios/issues/789#issuecomment-508114703

const data = new FormData();

data.append("firstFile", fs.createReadStream(firstFilePath), { knownLength: fs.statSync(firstFilePath).size });

const headers = {
    ...data.getHeaders(),
    "Content-Length": data.getLengthSync()
};

const endpoint = "http://pdf-doc-convert.example/convert/office";

const pdf = await axios.post(endpoint, data, config);