简体   繁体   中英

Node.js serving HTML file doesn't find referenced files

I'm trying to make a simple game using Node.js and HTML. I want to be able to run the game locally (so localhost). But when I start my Node server, only the HTML content is rendered - my images don't show up and the JS is not loaded. I reference JavaScript files, CSS files and images in the HTML code. Not sure why the server cannot reference these from within the HTML.

Here is my server code:

const path = require('path')
const http = require('http')
var fs = require('fs')

//Set port number:
const port = 3000

const requestHandler = (request, response) => {
    console.log(request.url)

    response.writeHead(200, {"Content-Type": "text/html"});
    response.end(fs.readFileSync('game.html'));

}

const server = http.createServer(requestHandler)
server.listen(port, (err) => {
    if (err) {
        return console.log('Error: ', err);
    }

    console.log(`Game started\nGo to http://localhost:3000 to play\n`);
    console.log(`Server is listening on ${port}...`);
})

Can anyone tell me how I can get my images/JS loaded? TIA

You need static handlers to return static content. Check this https://www.pabbly.com/tutorials/node-js-http-module-serving-static-files-html-css-images/ .

Also, if your application is going to be huge then use some middle-ware like Express. ( https://expressjs.com/ )

You are not serving the static content correctly (ie images, CSS). Consider what happens when one navigates to http://localhost:3000/some_image.png - they will be served game.html!

You need to account for users requesting that content in your requestHandler by for example reading the file they want with fs.readFileSync(request.url) . Remember to check that they can only request files you want them to be able to read!

If you use express framework, you can use static rendering:

app.use(express.static('public'));

where 'public' is the folder name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM