如果没有安装node js环境的请先配置环境
1.安装node。到Node官网下载安装即可,直接下一步下一步就完成了。
安装好了,我们打开cmd,输入命令行1:node -v, 这里是查询node版本,如果出现以下界面说明已经安装成功了。
通过node js中的文件模块,读取文件内容再渲到页面上
app.js
const http = require("http");
const fs = require("fs");
const server = http.createServer(function(req,res){
//设置响应头
res.writeHead(200,{"Content-Type":"text/html;charset=UTF-8"})
//设置访问的url路径
if(req.url == "/" || req.url == "/index"){
//路径为相对路径,也就是说与这个js文件同级的有一个html文件
fs.readFile("index.html",function(err,data){
res.writeHead(200,{"Content-Type":"text/html;charset=UTF-8"});
res.end(data);
});
}
})
server.listen(8080,function(){
console.log('running at 8080......');
});
index.html(放到和app.js同一级上)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Hello Nodejs</h1>
</body>
</html>
然后找到app.js,打开cmd
服务已运行在8080端口
访问localhost:8080/index