I have this in html
script src="./socket.io/socket.io.js"></script>
<script src="/src/chat/client.js"></script>
but in the browser, I get this error
GET
http://localhost:8080/socket.io/socket.io.js
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
server.js
const express = require('express');
const app = express();
const http = require('http').
createServer(app);
const socket = require('
socket.io
');
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');
});
Marmiz
January 29, 2019, 4:46am
2
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.html')
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
src/
index.htm
index.js
// index.html
<body>
<p>bla bla</p>
<script src="index.js"> </script>
</body>
Hope it helps
1 Like
i didn’t think about having to serve everything to the browser. putting things in a folder named public
makes sense now
Marmiz
January 29, 2019, 7:28am
4
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