Axios:数据应该是字符串、Buffer 或 Uint8Array

问题描述 投票:0回答:3

尝试使用 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 中有什么吗? 感谢您的帮助。

javascript node.js axios fs
3个回答
29
投票

在花了很多时间并尝试了很多可能的事情之后,我发现我得到的错误是。

TypeError: data should be a string, Buffer or Uint8Array

在我的 formData 中,我在文件中附加一个变量是

form.append('extractArchive', false);

这只不过是布尔值,axios 或 formData 对此给出了错误。 我把它改成了,

form.append('extractArchive', 'false');

这解决了我的问题。如果有人跑步遇到这样的问题,可能会有所帮助。

感谢您的帮助。


1
投票

这一行:

axios.post(reqUrl, form, request_config)

您在

FormData
参数中传递一个
form
对象。 Axios(在 NodeJS 中使用时)需要
string
Buffer
Uint8Array

当在浏览器中使用 Axios 时,它只是包装

fetch
,从而允许直接使用
FormData
),但是当在 NodeJS 中使用时,您需要序列化自己的请求正文(并且序列化为
multipart/form-data
可能会很痛苦,由于
Boundary
字段等)。

假设您实际上想要提出

multipart/form-data
请求,那么:


0
投票

更新axios

对于节点

npm i axios
© www.soinside.com 2019 - 2024. All rights reserved.