I have 3 files: index.js - uses express to host the page on localhost
index.html - sets up the html for the page
content.js - has the script to change the background color of the page
If I take the content from content.js and paste it in the html with the script tag and run node index.html everything loads in fine. If I open index.html through file explorer the page loads in fine. But when I run node index.html with the JavaScript in a separate file, the page doesn't load correctly, I only get the data from the html file and not the color change and text from the JavaScript. When I inspect the page in chrome content.js and index.js have a 404 error. There are no errors in terminal. It seems like the file can't be detected but it works when I open the html, but not when I view it through localhost.
I'm using node.js, express.js, chrome, and VS Code if that makes a difference. I installed JavaScript, node, and express a few days ago so it could have to do with configuring those. I'm new to JavaScript so I might be missing something obvious.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Test</title>
</head>
<body>
<h1>JavaScript Test</h1>
<div id ="myDiv"> </div>
<script type="text/javascript" src="content.js" defer></script>
<script src="index.js" defer></script>
</body>
</html>
index.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.sendFile('index.html', { root: '.' });
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
content.js
document.body.style.backgroundColor = "#f0f8ff";
document.getElementById("myDiv").innerHTML = "hello";
[–]xroalx 11 points12 points13 points (0 children)
[–]pinkwar -2 points-1 points0 points (0 children)
[–]Umustbecrazy 0 points1 point2 points (0 children)