尝试使用 axios 执行 POST 请求时遇到此错误:
TypeError: data should be a string, Buffer or Uint8Array
这是我的代码片段:
var fs = require('fs'),
axios = require('axios');
var FormData = require('form-data');
var form = new FormData();
form.append('file', fs.createReadStream("qa_test_file_DOC.txlf"));
form.append('extractArchive', false);
let request_config = {
headers: {
'Authorization': `Bearer eyJhbGciOiJIUzI1NXXXX.....`,
...form.getHeaders()
}
}
let reqUrl = "https://XXXXX/XX/rest/v1/XXXXX";
try {
axios.post(reqUrl, form, request_config)
.then(function (response) {
console.log(response);
return callback(response);
})
.catch(function (error) {
console.log(error);
return callback(error);
});
} catch (ex) {
console.log("exception ", ex);
}
尝试使用管道以及大多数可能的解决方案。文件存在。不明白这里出了什么问题。 Readstream 中有什么吗? 感谢您的帮助。
在花了很多时间并尝试了很多可能的事情之后,我发现我得到的错误是。
TypeError: data should be a string, Buffer or Uint8Array
在我的 formData 中,我在文件中附加一个变量是
form.append('extractArchive', false);
这只不过是布尔值,axios 或 formData 对此给出了错误。 我把它改成了,
form.append('extractArchive', 'false');
这解决了我的问题。如果有人跑步遇到这样的问题,可能会有所帮助。
感谢您的帮助。
这一行:
axios.post(reqUrl, form, request_config)
您在
FormData
参数中传递一个 form
对象。 Axios(在 NodeJS 中使用时)需要 string
、Buffer
或 Uint8Array
。
当在浏览器中使用 Axios 时,它只是包装
fetch
,从而允许直接使用 FormData
),但是当在 NodeJS 中使用时,您需要序列化自己的请求正文(并且序列化为 multipart/form-data
可能会很痛苦,由于 Boundary
字段等)。
假设您实际上想要提出
multipart/form-data
请求,那么:
请参阅此答案了解如何发送
multipart/form-data
:在 Node.js 中使用 axios 发布表单数据
这个 GitHub 问题:https://github.com/axios/axios/issues/789
更新axios
对于节点
npm i axios