How to post form data using Axios in node

前端 未结 1 572
忘了有多久
忘了有多久 2021-01-27 10:19

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 e

1条回答
  •  盖世英雄少女心
    2021-01-27 10:59

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

    0 讨论(0)
提交回复
热议问题