-1

Can someone please help me to understand what I am doing wrong with my code. Why won't my javascript or css file run when it is the server that sends the index.html file to the browser?

I have a very basic html page, javascript page, and express server. I am confused about something. If I get access to the html by starting the app and then typing: localhost:3000 in my url bar, the browser is served with the index.html as expected. However, none of the scripts in my javascript work (none of the console.logs run, and the event-handlers are not attached). On the other hand, if I paste the absolute file-path into the url bar (with or without the server running), the scripts.js file does work.

Here are my basic files:

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>music</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="scripts.js"></script>
  </head>
  <body>
    <p>I am the html</p>

    <button id="myButton">click here</button>

  </body>
</html>

scripts.js:

window.onload = function(e) { console.log('js file is loaded');
let button = document.getElementById('myButton');
button.addEventListener('click', function(e) { console.log('the button was clicked'); }); };

app.js

const express = require('express'); const app = express();

app.get('/', function (req, res) {
res.sendFile('/Users/myName/webPage/index.html'); });

app.listen(3000);

start server with: nodemon app.js

Thank you!

Maiya
  • 932
  • 2
  • 10
  • 26

1 Answers1

0

You are facing this issue because of the way you have configured your express server. Currently, according to the configuration be it any get request you serve the index.html file. Your JS, CSS, images etc are static files and you need to handle it a little differently.

Take a look at this link https://expressjs.com/en/starter/static-files.html. Modify your server.js file

const express = require('express'); const app = express();

app.use(express.static(__dirname + '/public')); //Add this line. Change public to whatever location your static assets are stored at

app.get('/', function (req, res) {
res.sendFile('/Users/myName/webPage/index.html'); 
});

app.listen(3000);
cdoshi
  • 2,772
  • 1
  • 13
  • 20