javascriptnode.jsaxiosform-datanode-request

nodejs - AxiosError: Request failed with status code 500


I am trying to convert the below code which is using request module to axios module to send the POST request.

request module code:

const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";

var options = {
    'method': 'POST',
    'url': url,
    'headers': {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        'Accept': 'application/json'
    },
    formData: {
    'image': {
            'value': imageFile,
            'options': {
            'filename': imgName,
            'contentType': null
            }
        }
    }
};

request(options, function (error, response) {
    if (error) throw new Error(error);
    console.log("SUCCESS");
});

The above code works fine and the image is posted successfully with the request module. But when I convert the same to axios, I am getting a 500 Error. (AxiosError: Request failed with status code 500)

axios module code:

const FormData = require('form-data')

const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";

const bodyFormData = new FormData();
bodyFormData.append("image['value']", imageFile);
bodyFormData.append("image['options']['filename']", imgName)
// bodyFormData.append("image['options']['contentType']", null)
console.log(bodyFormData)

const formHeaders = bodyFormData.getHeaders();

axios.post(url, bodyFormData, {
    headers: { 
    ...formHeaders, 
    'Cache-Control': 'no-cache',
    'Accept': 'application/json',
}
}).then(function (response) {
    console.log('SUCCESS');
}).catch(function (error) {
    throw new Error(error);
});

Can anyone find out what I am doing wrong here?

Is there any other way to post the image using axios other than using form-data?


Solution

  • See the documentation for FormData#append(). You can provide extra data like the file name as the 3rd options parameter

    const bodyFormData = new FormData();
    
    // Pass filename as a string
    bodyFormData.append("image", imageFile, imgName);
    
    // or to specify more meta-data, pass an object
    bodyFormData.append("image", imageFile, {
      filename: imgName,
      contentType: "image/jpeg",
    });
    
    axios.post(url, bodyFormData, {
      headers: {
        Accept: "application/json",
        "Cache-Control": "no-cache",
        ...bodyFormData.getHeaders(),
      },
    });
    

    Under the hood, request() does something very similar with the exact same form-data library. See request.js