Having an issue with express.static
.
My project is a basic portfolio website that includes a form for sending emails. I referred to this tutorial on Nodemailer: Tutorial Nodemailer Github
The problem arises within my index.html
file (this example applies to all .html files in the project) where I have:
<script src="/Public/index.js"></script>
for including my .js file.
Project folder structure can be seen here: Folder tree
When the script is included this way, no errors occur. However, upon sending an email, the webpage fails to load and does not redirect to /send.
If I include the script like so:
<script src="../index.js"></script>
It works correctly - the website redirects after sending the mail. But then I encounter this error message:
GET http://localhost:5000/index.js net::ERR_ABORTED 404 (Not Found)
I've looked into similar posts where incorrect usage of express.static
was identified as the issue. It seems likely that I made some mistakes with it, but I'm struggling to pinpoint them.
In my server.js
, I've added the following code for express.static
:
app.use("/Public", express.static(process.cwd() + "/Public"));
And for routing, I use:
app.route("/").get(function (req, res) {
res.sendFile(process.cwd() +"/Public/html/index.html");
});
Any assistance in understanding this issue would be greatly appreciated.
This is the index.js code snippet:
const form = document.getElementById("contact-form");
const formEvent = form.addEventListener("submit", (event) => {
event.preventDefault();
let mail = new FormData(form);
sendMail(mail);
});
const sendMail = (mail) => {
fetch("/send", {
method: "POST",
body: mail,
}).then((response) => {
return response.json;
});
};