How to post form data using Axios in node

依然范特西╮ 提交于 2021-02-05 10:01:32

问题


EDIT Changing the title so that it might be helpful to others

I am trying to upload an image to imgbb using their api using Axios, but keep getting an error response Empty upload source.

The API docs for imgbb shows the following example:

curl --location --request POST "https://api.imgbb.com/1/upload?key=YOUR_CLIENT_API_KEY" --form "image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"

My node code to replicate this is:

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

But I keep getting the following error response..

{
status_code: 400,
error: { message: 'Empty upload source.', code: 130, context: 'Exception' },
status_txt: 'Bad Request'
}

Not sure exactly where I am failing.

For the sake of completion and for others, how does the --location flag translate to an axios request?


回答1:


The issue was in the headers. When using form-data, you have to make sure to pass the headers generated by it to Axios. Answer was found here

headers: bodyData.getHeaders()

Working code is:

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


来源:https://stackoverflow.com/questions/55998715/how-to-post-form-data-using-axios-in-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!