Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HTML button not performing function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.');
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading