Why webpage refresh when we submit form with an image uploaded

Hello guys, I want a page to submit data without reloading. So I use the event.preventDefault() on my form and use the fetch API to send a request to my server. When I submit text fields only, like no image uploaded, I get the correct response and the web page isn't refresh. Now when I try to upload an image, I receive the response, a success response but the web page reloaded immediately, like as soon as response is sent, the web page is refresh, does someone know why please? The problem is surely because of the file upload because it only occur with the file being uploaded to the server.
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import multer from 'multer';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const profileRouter = express.Router();
const upload = multer({dest:'./SPA/Back-end/uploads/images'});

function logger(req,res,next) {
console.log(`The request path is ${req.path} and the request method is ${req.method}`);
next();
}

profileRouter.use(logger);

profileRouter.post('/image', upload.single('profilePic'), (req,res) => {
console.log(req.body, req.file);
res.status(200).json({ message: 'File uploaded successfully!' }); // Respond with JSON
});

export {profileRouter}
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import multer from 'multer';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const profileRouter = express.Router();
const upload = multer({dest:'./SPA/Back-end/uploads/images'});

function logger(req,res,next) {
console.log(`The request path is ${req.path} and the request method is ${req.method}`);
next();
}

profileRouter.use(logger);

profileRouter.post('/image', upload.single('profilePic'), (req,res) => {
console.log(req.body, req.file);
res.status(200).json({ message: 'File uploaded successfully!' }); // Respond with JSON
});

export {profileRouter}
31 Replies
Faker
FakerOP4w ago
here is the front-end script I'm using:
const inputFile = document.querySelector('#uploadFile');
const preview = document.querySelector('.preview');
const downLink = document.querySelector('a');

inputFile.addEventListener('change', () => {
console.log(`File selected is`, inputFile.files[0]);
const blob = new Blob([inputFile.files[0]], {'type': 'image/png'});
const url = URL.createObjectURL(blob); //give me a url for the image to be referenced
preview.src = url;
downLink.href = url;
downLink.download = 'PAC.png';
})

document.querySelector('#login').addEventListener('submit', (event) => {
event.preventDefault(); // Prevent default form submission

const formData = new FormData(event.target);
console.log(event.target);

fetch('http://localhost:8080/M00967932/api/image', {
method: 'POST', // Specify the HTTP method
body: formData, // Send the FormData object
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.text(); // If server sends text or HTML
})
.then((data) => {
console.log('Success', data); // Handle success with text or HTML response
})
.catch((error) => {
console.error('Error:', error); // Handle errors
});
});
const inputFile = document.querySelector('#uploadFile');
const preview = document.querySelector('.preview');
const downLink = document.querySelector('a');

inputFile.addEventListener('change', () => {
console.log(`File selected is`, inputFile.files[0]);
const blob = new Blob([inputFile.files[0]], {'type': 'image/png'});
const url = URL.createObjectURL(blob); //give me a url for the image to be referenced
preview.src = url;
downLink.href = url;
downLink.download = 'PAC.png';
})

document.querySelector('#login').addEventListener('submit', (event) => {
event.preventDefault(); // Prevent default form submission

const formData = new FormData(event.target);
console.log(event.target);

fetch('http://localhost:8080/M00967932/api/image', {
method: 'POST', // Specify the HTTP method
body: formData, // Send the FormData object
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.text(); // If server sends text or HTML
})
.then((data) => {
console.log('Success', data); // Handle success with text or HTML response
})
.catch((error) => {
console.error('Error:', error); // Handle errors
});
});
ἔρως
ἔρως4w ago
preserve the log and try again im 300% sure you have a mistake somewhere that throws an exception
Faker
FakerOP4w ago
Hmmm preserve the log, is there an option in chrome or should write some code like logging everything in a file ?
ἔρως
ἔρως4w ago
it's an option in the f12 tools
Faker
FakerOP4w ago
oh didn't know we can preserve the log, thanks
Faker
FakerOP4w ago
here is what I obtain
No description
Faker
FakerOP4w ago
there is no error status code though
Faker
FakerOP4w ago
This problem occur only when we try to upload an img file
No description
Faker
FakerOP4w ago
here for e.g, I didn't upload any file from the file picker
ἔρως
ἔρως4w ago
and in the console?
Faker
FakerOP4w ago
hmm the console refreshes
ἔρως
ἔρως4w ago
preserve the log then
Faker
FakerOP4w ago
hmm I'm not finding the option for this one :c
ἔρως
ἔρως4w ago
its under the tab list, on the left
Faker
FakerOP4w ago
ahh wait
Faker
FakerOP4w ago
No description
Faker
FakerOP4w ago
yeah got it, it navigates me to the current url but why
ἔρως
ἔρως4w ago
good question nothing stands out
glutonium
glutonium4w ago
upload.single('profilePic'), () => {})
upload.single('profilePic'), () => {})
i think u have an extra ')' after the profilePic ooh wait nvm i got it wrong i am reading on mobile so the code is f-ed up could it be due to the creation of blob? idk why u r using blob here
ἔρως
ἔρως4w ago
to show the image
glutonium
glutonium4w ago
hmm i see Faker, can you try commenting out that part and see if webpage refreshes or something? also make sure u have the correct selector in the querySelector, #login just to be sure if it doesn't refresh after commenting out then u can try a different method for showing the image on the webpage. not sure how but i think FileReader class might help here
Faker
FakerOP4w ago
hmm even when I comment the blob thing, I still get the "navigated to url" yep the selector is correct, the problem arises only with the file upload I don't understand, this is strange
ἔρως
ἔρως4w ago
can you put this somewhere where we can test?
Faker
FakerOP4w ago
euh I have a github I never use it though, I don't really know how it works but I can try uploading the code there the problem is the window, the browser is renavigating, like there is a redirection some default behaviour of the form I don't know :c
ἔρως
ἔρως4w ago
it can be anything, but without actually seeing it, it's impossible to say
Faker
FakerOP4w ago
even chatgpt is not giving me an answer :c
ἔρως
ἔρως4w ago
you dont know enough to use chatgpt without being bamboozled
Faker
FakerOP4w ago
hmm I can paste the code here if you want ohhh ok I think I might know the error Initially, I was using live server extension to open my html file, then from that port I was communicating to my back-end found on another port Now the thing is each time I upload the file, behind the scenes in my back-end an upload folder is being created and the blob appended there from what chatgpt has given me: The VS Code Live Server plugin might reload the page when it detects file changes in your project directory. This could cause navigation even though your code is correct. Which is correct, because in fact the problem of the page reloading, didn't arise the first time, this is because I created the upload directory outside of my project directoy but when I change the path and the upload folder was now in the project directory, this gives me the error so I believe the problem was the live server extension being refreshed each time there is a change in the uploads folder
ἔρως
ἔρως4w ago
it sounds plausible, but i can't say
Faker
FakerOP4w ago
I believe that was the reason, instead of using live server, I just switch to my express server and works fine now... I should test by removing the upload folder in my project directory but will do that later on, this bug was really tiring :c
ἔρως
ἔρως4w ago
it does sound plausible, but i really have nothing to add or "debunk" from what you said
Want results from more Discord servers?
Add your server