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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM