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

时间:2019-05-06 04:13:10

标签: node.js axios

EDIT (更改标题),以便对他人有帮助

我正在尝试使用Axios的api将图像上传到imgbb,但始终收到错误响应Empty upload source

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请求?

1 个答案:

答案 0 :(得分:0)

问题出在标题中。使用form-data时,必须确保将其生成的标头传递给Axios。找到了答案here

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));