我正在开发一个学校项目,我计划使用 Node.js 来托管它。问题是,每次我尝试运行它时,它都不会返回任何内容。 我在一个文件夹中有 4 个 HTML、2 个 CSS 和 2 个 JS 文件,我正在尝试托管所有 HTML 文件。
我的node.js脚本:
var http = require('http');
var fs = require('fs');
const PORT=8080;
fs.readFile('./index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(PORT);
})
但终端没有返回任何内容。
您的代码不适合托管既不简单也不复杂的网页。
无论如何,我将向您解释如何使用您的代码解决您的问题,并且我将向您展示另一个专业提示
您的代码正在运行。只需访问 http://localhost:8080/ 即可验证它
但是如果您有其他文件,例如 foo.html ,您的代码将无法工作。您可以添加更多
fs.readFile
和逻辑来渲染它们,例如
var http = require('http');
var fs = require('fs');
async function main(){
const PORT=8080;
var page1 = await fs.promises.readFile('./index.html');
var page2 = await fs.promises.readFile('./index2.html');
var page3 = await fs.promises.readFile('./index3.html');
http.createServer(function(request, response) {
var pageContent;
if(request.url=="/" || request.url.endsWith("index.html")){
pageContent = page1;
}else if(request.url.endsWith("index2.html")){
pageContent = page2;
}else if(request.url.endsWith("index3.html")){
pageContent = page3;
}else {
pageContent = "Page not found";
}
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(pageContent);
response.end();
}).listen(PORT);
}
main();
结果
如您所见,它可以工作,但是您需要为每个新文件(css、js、字体等)添加更多逻辑,这是没有意义的。无论如何,如果您坚持从头开始编码(这可以帮助您了解真正的服务器有多复杂),您可以使用名为 express 的库:
var express = require('express');
var app = express();
// set the port of our application
var port = process.env.PORT || 8080;
// make express look in the public directory for assets (css/js/img)
app.use(express.static(__dirname+"/web"));
// set the home page route
app.get('/', function(req, res) {
res.sendFile('index.html');
});
app.listen(port, function() {
console.log('Our app is running on ' + port);
});
在 web 文件夹中放置所有文件(js、css、字体等)和 N 个 html 文件
注释
http://localhost:8080/foo.html
库:https://www.npmjs.com/package/node-static
用途:
在包含所有文件的文件夹中,执行
npm install -g node-static
static
然后访问http://localhost:8080
注释
如果您需要在笔记本电脑/个人电脑之外向老师或团队展示您的页面,我可以建议使用 github 页面。这样您就可以共享公共链接,其他人可以使用互联网查看您的网站。
更多详情
还有另一种选项用于真实企业托管真实网站: