How do I link a Js file to index.html that was served to the browser (

I have this in html

script src="./"></script>

<script src="/src/chat/client.js"></script>

but in the browser, I get this error

GET http://localhost:8080/ net:: ERR_ABORTED 404 (Not Found)

GET http://localhost:8080/src/chat/client.js net:: ERR_ABORTED 404 (Not Found)

the files exist but its not find them after the html gets served


const express = require('express');

const app = express();

const http = require('http').


const socket = require(' ');

const io = socket(http);

const port = 8080;

app.listen(port, () => console.log(\listening on ${port}\ ));`

app.get('/', (req, res) => {

res.sendFile('/index.html', { root: __dirname.replace(/src$/, '') }


// talk to browser

io.on('connection', socket => {

console.log('a user has connected');


You have to serve the JS files as well, otherwise you are only “sending back” the html, hence the 404 errors.

However sendFile close the response so I don’t think you can:

res.sendFile('index.js') // the response gets closed.

You probably want to use express static middleware:

1 - app.use middleware defaults to '/'
2 - static is relative to the directory where you launch node. Perhaps you need some path method as well
app.use(express.static(path.join(__dirname, 'src')))

edit: the above will serve all the content from a src folder so in a case of

// index.html
  <p>bla bla</p>
  <script src="index.js"> </script> 

Hope it helps :+1:

1 Like

i didn’t think about having to serve everything to the browser. putting things in a folder named public makes sense now

You don’t have to send everything with the response,
you could have a script in the html that ask the server for additional data / file…

but it’s a bit “odd” since you’d have to send two requests for something that could be done only in one :slight_smile: