当前位置:网站首页>---static page---

---static page---

2022-08-02 03:42:00 cjx177187

01.Html文件

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <link rel="stylesheet" href="./01.css">

</head>

<body>

   

    <img src="./1.png" >

    <img src="https://p3.ssl.qhimg.com/dmfd/400_300_/t0140582dc583d923bf.png" >

    <a href="./02.html">网页2</a>

    <a href="https://www.baidu.com">百度</a>

</body>

</html>

 

node.js代码

var http=require("http")

var fs=require("fs")

var app=http.createServer((req,res)=>{

    if(req.url=="/01.html"){

        fs.readFile(__dirname+"/01.html",(err,data)=>{

            res.end(data)

        })

    }else if(req.url=="/1.jpg"){

        fs.readFile(__dirname+"/1.jpg",(err,data)=>{

            res.end(data)

        })

    }else if(req.url=="/02.html"){

        fs.readFile(__dirname+"/02.html",(err,data)=>{

            res.end(data)

        })

    }

})

app.listen(8081)

 

 

 

When we enter the URL in the browser,Received is the source code of the webpage,How does this code browser work?,It runs line by line from top to bottom;Parse nodes in a document tree,A node-by-node parsing,当解析到 <link rel="stylesheet" href="./01.css">代码时,It will spontaneously make a request to the backend,再次运行http.createServer这个函数,This is the browser will receive a copycss代码,然后再渲染到页面上,再回到HTMLRun the next line of code on the file,一直运行到

 <img src="./1.png" >  时 再次 发送请求调用http.createServer,获取1.pngThis image is rendered on the page,Execute line by line like this,Time and time again to send the request to accept data,The last page we see. 

 

但是我们会发现,Our code needs to check again and again to determine the network address we are requesting and whether we are what we want,If we are using

fs.readFilefunction to read data and send it to the front end,In this way, we need to write a web page many timesifelse语句,And many lines of code are actually similar,It only changes our judgment conditions and the data to be read.We will also find a little,That is, the statement we are going to judge is actually the same as the file name we want to read first, but an absolute path is added before the statement we want to read..

 

So we can try to imagine why we can't put the judgment statement and the read file path as a variable into our code.,This replaces all of ourif判断了

 

 

 改进:

var http=require("http")

var fs=require("fs")

var app=http.createServer((req,res)=>{

    fs.readFile(__dirname+req.url,(err,data)=>{

        res.end(data)

    })

})

app.listen(8081)

 

 

 

原网站

版权声明
本文为[cjx177187]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208020321320224.html