[英]Node.js serving HTML file doesn't find referenced files
I'm trying to make a simple game using Node.js and HTML. 我正在尝试使用Node.js和HTML制作一个简单的游戏。 I want to be able to run the game locally (so localhost).
我希望能够在本地运行游戏(因此是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.
但是,当我启动Node服务器时,仅呈现HTML内容-我的图像没有显示并且JS未加载。 I reference JavaScript files, CSS files and images in the HTML code.
我在HTML代码中引用了JavaScript文件,CSS文件和图像。 Not sure why the server cannot reference these from within the HTML.
不知道为什么服务器无法从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? 谁能告诉我如何加载图像/ JS? TIA
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/ .
检查此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. 另外,如果您的应用程序将变得庞大,则可以使用某些中间件,例如Express。 ( https://expressjs.com/ )
( https://expressjs.com/ )
You are not serving the static content correctly (ie images, CSS). 您没有正确提供静态内容(即图像,CSS)。 Consider what happens when one navigates to
http://localhost:3000/some_image.png
- they will be served game.html! 考虑一下当浏览到
http://localhost:3000/some_image.png
时会发生http://localhost:3000/some_image.png
-将向他们提供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)
. 您需要考虑用户在
requestHandler
请求该内容的问题,例如,使用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 其中“ public”是文件夹名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.