app.js里面的代码:
var http = require("http"); // 用于web服务器
var path = require('path'); // 用于路径操作
var fs = require('fs'); // 用于文件操作
var static = require('node-static'); // 用于提供静态资源
var staticServer = new static.Server('./public'); // 将public目录作为静态资源目录
function handleStaticRequest(req, res) { // 处理静态资源请求
req.addListener('end', function () { // 监听HTTP请求结束事件
staticServer.serve(req, res); // 提供静态资源服务
}).resume();
}
var app = http.createServer(function(req, res) { // 创建WEB服务器
handleStaticRequest(req, res); // 处理静态资源请求
});
app.listen(8080, function(){ // 监听8080端口
console.log("listen at port http://localhost:8080");
});
在vs code里面建立一个新终端,输入 node app.js运行后,报错:Cannot find module ‘node-static’,
百度之后说需要输入npm install node-static -g,但是实操后还是不行,最后发现在项目文件夹目录处建立一个新终端,然后输入npm install node-static运行,下载好后,在命令行里面进入项目文件夹目录,然后执行node app.js,然后会出现下图
然后进入浏览器,输入http://localhost:8080/index.html,运行后就能看见代码应该显示的页面