[英]Style and javascript files not applied to page that is serving HTML in Node.js
[英]Node.js serving HTML file doesn't find referenced files
我正在嘗試使用Node.js和HTML制作一個簡單的游戲。 我希望能夠在本地運行游戲(因此是localhost)。 但是,當我啟動Node服務器時,僅呈現HTML內容-我的圖像沒有顯示並且JS未加載。 我在HTML代碼中引用了JavaScript文件,CSS文件和圖像。 不知道為什么服務器無法從HTML內引用這些內容。
這是我的服務器代碼:
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}...`);
})
誰能告訴我如何加載圖像/ JS? TIA
您需要靜態處理程序以返回靜態內容。 檢查此https://www.pabbly.com/tutorials/node-js-http-module-serving-static-files-html-css-images/ 。
另外,如果您的應用程序將變得龐大,則可以使用某些中間件,例如Express。 ( https://expressjs.com/ )
您沒有正確提供靜態內容(即圖像,CSS)。 考慮一下當瀏覽到http://localhost:3000/some_image.png
時會發生http://localhost:3000/some_image.png
-將向他們提供game.html!
您需要考慮用戶在requestHandler
請求該內容的問題,例如,使用fs.readFileSync(request.url)
讀取他們想要的文件。 切記檢查它們是否只能請求您希望它們能夠讀取的文件!
如果使用快速框架,則可以使用靜態渲染:
app.use(express.static('public'));
其中“ public”是文件夾名稱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.