axios多部分请求失败

时间:2019-09-24 14:56:05

标签: node.js post axios multipartform-data

我正在尝试发送一项使用服务将doc转换为pdf的帖子请求。该服务与邮递员合作良好,您可以将doc发送到端点,然后将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请求的简单文章(带有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);
}

我如何提出请求?

1 个答案:

答案 0 :(得分:1)

也许最快的调试方法是使用Postman Intercept截获您通过Axios请求发出的呼叫,并比较有效的cURL请求信息和无效的cURL请求信息。可能是标题问题或文件编码问题。

我之前遇到过类似的情况,这可能与formData标头有关,该标头需要在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);