node+express的html页面访问

node+express访问himl文件的入门实例

1.首先在需要操作的文件夹下安装express模块

  D:\vs code\File\hrml\mysqlweblod> npm install express 

2.创建index.js文件,如下

 1 //引入exprexx模块
 2 var express =require("express");
 3 var app =express();
 4 app.use(express.static('public'))
 5 
 6 //参数‘/’可当作设置url的根显示页面,这里即”http://localhost:3000/“访问的页面设置为index.html
 7 app.get('/',(req,res)=>{
 8     res.sendFile(__dirname+"/"+"index.html")        //设置/ 下访问文件位置
 9 });
10 
11 //参数‘/tow’可当作设置url的/tow下显示页面,这里即”http://localhost:3000/tow“访问的页面设置为index2.html
12 app.get("/tow",(req,res)=>{
13     res.sendFile(__dirname+"/"+"index2.html")        //设置/tow下访问文件位置
14 })
15 
16 //设置端口3000访问地址,即http://localhost:3000
17 var server =app.listen(3000,()=>{
18     var port =server.address().port
19     console.log("【】访问地址http://localhost:%s",port)
20 })

3.创建index.html和index2.html测试文件;

index.html

<p>Holle word</p>

index.html

<meta charset="utf-8">
<p>我是index2</p>

4.测试

在当前文件目录终端下输入:node. index.js

  D:\vs code\File\hrml\mysqlweblod> node index.js 

访问 http://localhost:3000 显示

Holle word

访问 http://localhost:3000/tow 显示

我是index2

猜你喜欢

转载自www.cnblogs.com/hmcjsc/p/12704350.html