I have created an endpoint to upload an avatar with my nodeJS API.
The endpoint works fine when I use it from POSTMAN.
But it doesn't work when I call it with Fetch from my react-js app.
When I use Fetch to call the endpoint, the busboy.on('file', () = {...}) seems to be not triggered.
The fetch method in my react-js app:
export const fetchPostFile = async (url, file) => {
try {
const data = new FormData();
data.append("image", file);
const rawResponse = await fetch(url, {
method: 'POST',
body: data
});
return await rawResponse.json();
} catch (error) {
console.error(error);
return {success: false, message: 'query_can_not_be_sent'};
}
}
The input formData sent by reactjs:
------WebKitFormBoundary5WI3GuEx81A7nLq0
Content-Disposition: form-data; name="image"
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/7QL6UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAt0cAQAAAgACHAEUAAIAARwBFgACAAIcAR4ACUFGUC1QSE9UTxwBKAAIMTIzNDU2NzgcATwAATUcAUYACDIwMjAxMDExHAFQAAsxNTU5MjcrMDAwMBwBWgADGy1BHAFkAApBRlBfOFJWOUFQHAIAAAIAAhwCBQAZVEVOTklTLUZSQS1PUEVOLU1F...
The api method to upload the avatar
exports.postAvatar = async (request, response) => {
response.set('Access-Control-Allow-Origin', '*');
response.set('Access-Control-Allow-Headers', '*');
const BusBoy = require('busboy');
const fs = require('fs');
const os = require('os');
const path = require('path');
const busboy = new BusBoy({ headers: request.headers });
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
console.log('busboy.on(file)');
});
busboy.on('finish', async () => {
console.log('busboy.on(finish)');
});
busboy.end(request.rawBody);
return response.json({message: 'ok'});
}
busboy.on(file)
message is not displayed when I call from reactjs but it is displayed with a postman call.
EDIT:
I checked the POSTMAN input and the image is not sent as base64 but like this:
In Postman, I tried with a base64 picture in a field text in input and I have the same result that with Fetch.
Is busboy can receive a base64 encoded image ? Or can I convert the base64 picture to a file input ?