This answer quotes ChatGPT
This error usually means that the form is incorrectly formatted or that some necessary form field or tag is missing. In your code, I notice that you send the XMLHttpRequest request with the Content-type header set to multipart/form-data. This is correct, but you use a random delimiter to generate the form boundary identifier. This can result in incorrectly formatted forms.
Instead, you can use FormData objects to build form data. FormData automatically generates boundary identifiers for you. You can modify your front-end code like this:
btn.addEventListener('click',function(){
let formdata = new FormData();
formdata.append('avatar',file);
const xml = new XMLHttpRequest();
xml.open('post','http://localhost:3000/api/swiper',true);
xml.onlonreadystatechangeoad = function(){
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xml.send(formdata);
});
In your back-end code, you use Multer middleware to handle file uploads. Note that the upload.single() method processes only one file and stores it in req.file. Therefore, instead of using req.files, you can use req.file to retrieve uploaded files. In addition, if an error occurs, Multer stores the error in the MulterError object, and you can use the instanceof operator to check if such an error exists. In your code, you can modify the back-end code like this:
router.post('/', upload.single('avatar'), (req, res) => {
try {
console.log('file', req.file);
console.log('body', req.body);
} catch (err) {
if (err instanceof multer.MulterError) {
console.log(err.code);
} else {
console.log(err);
}
res.status(500).send(err);
}
});