I was receiving the following error in the client while executing a callback function:
Error: ENOENT: no such file or directory, stat 'C:\Users\38163\Downloads\Account-Manager-App-Express-MongoDB-main\Account-Manager-App-Express-MongoDB-main\src\tempelates\successfulRegistration.html'
Here is the callback function I was using here:
app.post("/register", async (req, res) => {
try {
const { username, email, password, confirmPassword } = req.body;
// Ensure passwords match
if (password !== confirmPassword) {
return res.status(400).send("Passwords do not match");
}
// Check if user already exists
const existingUser = await UserCollection.findOne({ email });
if (existingUser) return res.status(400).send("User already registered");
// Hash password before saving
const hashedPassword = await bcrypt.hash(password, 10);
// Log the hashed password for debugging
console.log("Hashed Password:", hashedPassword); // Compare with what's saved in the database
// Save user in UserCollection
const newUser = new UserCollection({ username, email, password: hashedPassword });
await newUser.save();
res.sendFile(path.join(__dirname, 'tempelates', 'successfulRegistration.html'));
} catch (error) {
console.error(error);
res.status(500).send("Error during registration");
}
});
In bolded you can see the part of the code that was actually encountering the issue.
1. Path Issues:
Incorrect Path: The most likely problem is that the path I was constructing is incorrect. path.join(__dirname, 'tempelates', 'successfulRegistration.html')
relies on __dirname
which represents the directory of the current file. If your registration route handler is in a different directory than the tempelates
folder, the path will be wrong.
2. Solution:
Relative Path from Project Root: This is the most robust approach. It makes your code less dependent on the specific location of the route handler file.
const path = require('path'); // Make sure path is required
// Get the absolute path to your project's root directory. Adjust as necessary.
const projectRoot = path.join(__dirname, '..'); // Assuming 'src' is directly under the project root.
//If your folder is directly under the project root use:
//const projectRoot = __dirname;
const successfulRegistrationPath = path.join(projectRoot, 'tempelates', 'successfulRegistration.html');
app.post("/register", async (req, res) => {
// ... your existing code ...
res.sendFile(successfulRegistrationPath);
});