I was using express and the render function to load different pages of my website. However, I have decided to just go with vanilla js instead. The goal is to load the html file and all the js/css stuff too. Here is my code:
server:
const http = require('http');
const fs = require('fs');
http.createServer((req,res) => {
res.writeHead(200, {'Content-type': 'text/html'})
fs.readFile('./index.html', null, (err, data) => {
if(err){
res.writeHead(404);
res.write('File not found')
}else{
res.write(data)
}
res.end();
})
}).listen(3000);
html file:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./styles/main.css">
<script src="./src/global.js" defer></script>
<title>Test</title>
</head>
<body>
<div id="scene-lobby" >
hello this is a test
</div>
<button id="button1">click me</button>
</body>
</html>
when I load the webpage, the html file loads, but the css and javascript don't. Also, I get this error regarding the javascript file:
Uncaught SyntaxError: Unexpected token '<' (at global.js:1:1)
Does anyone know how to fix this?
CodePudding user response:
The way a browser works is that it load an HTML page, parses it and then finds other resources such as css files, images, etc... that need loading. It then makes a separate http request to your server for those other resources. Thus, your server MUST know how to respond to those requests and serve the appropriate resource that is being requested.
The http server you show sends index.html
for ALL requests it receives. Thus, when the browser requests the CSS file, your server sends index.html
which is completely invalid CSS. Your server needs separate routes for each resource that your web page contains.
It's common to create a generic route that serves a number of static resources based on what was requested and what exists in a specific directory that contains only files that are expected to be served. When using the Express mini-framework, that can be done with one line of code in express.static()
. If you're going to roll your own http server from scratch, you would need to either handle each static resource separately or build your own equivalent to express.static()
.