I have 3 files:
index.html:
<html>
<head>
</head>
<body>
<h1>Webpage</h1>
<p id = "text">Hello world!</p>
<button onclick = "myButton()">Click me!</button>
<script src="./page.js"></script>
</body>
</html>
server.js:
const express = require('express');
const app = express()
const port = 8000
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.listen(port, () => {
console.log('Server started.')
});
and page.js:
function myButton() {
document.getElementById('text').innerHTML = 'Hi world!';
}
When I open the HTML file manually from file explorer, the button changes the text as its supposed to. However, when I run server.js and then visit localhost, the button doesn’t work. Can someone help me understand what’s going wrong?
>Solution :
Based on your problems, it appears that the issue lies in serving static files (like your page.js) through your Express server. When you open the HTML file directly from the file explorer, your browser can access page.js because it’s in the same directory. However, when you serve the HTML file through an Express server, you also need to explicitly tell the server to serve static files like JavaScript files, CSS files, images, etc.
What you should do:
Move your index.html, page.js, and any other static files (like CSS files) into a directory named public within your project directory. This is a common convention for Express applications.
Update the app.use(express.static(‘public’));
This express.static middleware tells Express to serve all static files from the public directory. When you make a request to your server, Express will first check if there’s a static file that matches the request path in the public directory and serve it if found.
// Serve static files from 'public' directory
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.listen(port, () => {
console.log('Server started.');
});