Kevin Powell - CommunityKP-C
Kevin Powell - Community14mo ago
54 replies
Faker

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}
Was this page helpful?