Node.js 如何在节点中使用Axios发布表单数据

Node.js 如何在节点中使用Axios发布表单数据,node.js,axios,Node.js,Axios,编辑更改标题,以便对其他人有所帮助 我正试图使用Axios使用他们的api将图像上载到,但不断收到错误响应空上载源文件 imgbb的API文档显示了以下示例: curl --location --request POST "https://api.imgbb.com/1/upload?key=YOUR_CLIENT_API_KEY" --form "image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" 我要复制的节点代码

编辑更改标题,以便对其他人有所帮助

我正试图使用Axios使用他们的api将图像上载到,但不断收到错误响应
空上载源文件

imgbb的API文档显示了以下示例:

curl --location --request POST "https://api.imgbb.com/1/upload?key=YOUR_CLIENT_API_KEY" --form "image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
我要复制的节点代码是:

    const fs = require('fs')
const FormData = require('form-data')
const Axios = require('axios').default

let file = '/tmp/the-test.png'
let url = 'https://api.imgbb.com/1/upload?key=myapikey'
var bodyData = new FormData();
let b = fs.readFileSync(file, {encoding: 'base64'})
bodyData.append('image', b)
Axios({
  method: 'post',
  url: 'url',
  headers: {'Content-Type': 'multipart/form-data' },
  data: {
    image: bodyData
  }
}).then((resolve) => {
  console.log(resolve.data);
}).catch(error => console.log(error.response.data));
但我一直得到以下错误响应

{
status_code: 400,
error: { message: 'Empty upload source.', code: 130, context: 'Exception' },
status_txt: 'Bad Request'
}
不知道我到底在哪里失败了


为了完成和其他方面,如何将
--location
标志转换为axios请求?

问题在标题中。使用
表单数据时
,必须确保将其生成的标题传递给Axios。找到了答案

headers:bodyData.getHeaders()

工作守则如下:

const fs = require('fs');
const FormData = require('form-data');
const Axios = require('axios').default;

let file = '/tmp/the-test.png';
var bodyData = new FormData();
let b = fs.readFileSync(file, { encoding: 'base64' });
bodyData.append('image', b);
Axios({
  method  : 'post',
  url     : 'https://api.imgbb.com/1/upload?key=myapikey',
  headers : bodyData.getHeaders(),
  data    : bodyData
})
  .then((resolve) => {
    console.log(resolve.data);
  })
  .catch((error) => console.log(error.response.data));

非常感谢!!!这个答案救了我!非常感谢你!