I am recieving files using node js on another computer and I want to send custom metadata from the computer I am uploading from. addonData
is an {} object with key value pairs that have information about the files I’m uploading. I am using formData.append
to add addonData, but on my server console.log(req.body)
returns {}
(req has tons of data including req.body: {},
).
const app = express();
app.use(express.json());
...
async function uploadFile(filePath, uploadUrl, fileName, addonData) {
...
formData.append('file', fileBuffer, fileName);
formData.append('addonData', '[' + JSON.stringify(addonData) + ']');
// Perform the fetch request to upload the file
const response = await fetch(uploadUrl, {
method: 'POST',
body: formData, // Automatically sets 'Content-Type': 'multipart/form-data'
});
...
}
Then on my computer recieving the uploads:
const app = express();
app.use(express.json());
...
POST route for handling file uploads
app.post('/upload', (req, res) => {
const form = new formidable.IncomingForm({
uploadDir: uploadDirectory,
keepExtensions: true,
keepFilenames: true,
filename: function (name, ext, part) {
// Use the original filename
return part.originalFilename;
}
})
form.parse(req, (err, fields, files) => {
if (err) {
console.error('Error processing upload:', err);
return res.status(500).send('An error occurred during the upload.');
}
console.log(req.body) // returns {}
addonDataStr = req.body.addonData; // undefined
addonData = JSON.parse(addonDataStr);
// Update addonData
addonData.new_filename = files.file[0].newFilename;
addonData.path_server = files.file[0].filepath;
addonData.size_bytes = files.file[0].size;
addonData.IP = req.ip;
addonData.req_headers = req.headers;
appendFileNameKey();
res.status(200).send('File uploaded successfully.');
});
});
When I try to add headers: {'Content-Type': 'application/json'}
to the first script the server gives the error “Unexpected token – in JSON at position 0”. The files are uploading correctly using the code above if I comment out trying to receive metadata (addonData). Thanks for the help.