i am mern stack developer and i don’t have any experience in this field. I have tried all method to solve the below problem but it gives error
my template file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Fontawesome -->
<script
src="https://kit.fontawesome.com/42a182743f.js"
crossorigin="anonymous"
></script>
<!-- CSS -->
<link rel="stylesheet" href="/css/uploadPhoto.css" />
<title>Upload Profile Photo</title>
</head>
<body>
<!-- nav-bar -->
<%- include("../partials/navbar") %>
<div class="form-container">
<!-- icon -->
<h1>Upload Profile photo</h1>
<p>
<!-- upload icon -->
</p>
<small class="error">
<% if (uploadedImage) { %>
<i class="fas fa-exclamation-circle"></i>
<%= uploadedImage %>
<% } %>
</small>
<form action="/api/v1/users/profile-photo-upload?_method=PUT" method="POST" enctype="multipart/form-data">
<label for="email">Select Image</label>
<input type="file" name="profile" id="image" />
<button type="submit">
<i class="fas fa-upload"></i>
</button>
</form>
</div>
<!-- footer -->
<%- include("../partials/footer") %>
</body>
</html>
and my server file is,
app.put("/profile",async (req,res,next)=>{
try {
//check if no file if upload
if(!req.file) return next(appErr("No profile image is uploaded"));
//find the user to be updated
const userID = req.session.userAuth;
const findUser = await User.findById(userID);
//if user not found
if(!findUser) return next(appErr("User not found",403));
//update profile photo
const newUser = await User.findByIdAndUpdate(userID,{
profileImage: req.file.path
},{
new: true
});
//if new file is uploaded then delete old one
if(req.file && findUser.profileImage !== undefined){
const public_id = extractPublicId(findUser.profileImage);
cloudinary.uploader.destroy(public_id)
};
res.locals.uploadedImage = "Image Uploaded";
res.render("users/uploadProfilePhoto");
} catch (error) {
return next(appErr(error.message));
}
};);
so the problem is that every time i access uploadedImage
in template file it gives error uploadedImage is undefined
but when i use res.locals.uploadedImage
in middleware it perfectly worked
app.use((req,res,next)=>{
if(req.session.userAuth){
res.locals.uploadedImage = "File Uploaded";
}else{
res.locals.uploadedImage = null;
}
next();
});
can someone explain me why res.locals.uploadedImage
work with middleware and not work with route and please provide some solution?
i want the solution of the above code and want to know that why res.locals.uploadedImage
works perfectly with middleware but gives error when it is used in a route
GAMING WARRIOR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.