Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  151] [ 5]  / answers: 1 / hits: 5759  / 2 Years ago, tue, august 2, 2022, 12:00:00

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?


More From » node.js

 Answers
5

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


[#46] Wednesday, July 6, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamila

Total Points: 490
Total Questions: 94
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;