Hello I am trying to design a very simple web application with Express.js
that just sends your email address that you submitted to the server side. But when I try to combine normal JavaScript (like querySelector
) with code that has Express.js
contents, it does not work and crashes saying that document
in document.getElementById("email")
is not defined. May I ask if there is a way to do this? Or how should I send data from the client side to the server side and vice versa properly?
This is my first very simple project in web development so the code is not the best.
JavaScript Code
const express = require("express")
const app = express();
const path = require("path")
app.use(express.static("./"))
app.listen(5000, () => {
console.log("Server listening on port 5000...")
})
app.get("/", (req, res) => {
res.sendFile("index.html", (err) => {
console.log(err)
})
})
let enterEmail = document.getElementById("email")
let submit = document.getElementById("submit")
let status = document.getElementById("status")
let email;
submit.addEventListener("click", (e) => {
email = enterEmail.value
enterEmail.value = ""
status.innerHTML = "Submitted email: " + email;
})
HTML Code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<input id ="email" placeholder="enter email" type="text"></input>
<input id="submit" type="submit">
<h1 id="status">Submitted email: </h1>
<script src="./index.js"></script>
</body>
</html>
The error message:
let enterEmail = document.getElementById("email")
^
ReferenceError: document is not defined
at Object.<anonymous> (C:\Users\Lenovo\Desktop\personal-projects\app.js:23:18)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
[nodemon] app crashed - waiting for file changes before starting...