前言

 我是歌谣 今天给大家带来的是关于node中http模块的一个讲解

 案例1

const http=require("http")
//创建服务器
http.createServer(()=>{
  
}).listen(3002,()=>{
    console.log("geyao.....")
})

运行结果

node之http模块_html

 案例2

const http=require("http")
//创建服务器
http.createServer((req,res)=>{
    res.write("hello geyao1")
    res.end()
    
}).listen(3002,()=>{
    console.log("geyao.....")
})

 运行结果

node之http模块_html_02

 案例3

const http=require("http")
//创建服务器
http.createServer((req,res)=>{
    res.write(`<html>
        <p>hello geyao</p>
    </html>`)
    res.end()
    
}).listen(3002,()=>{
    console.log("geyao.....")
})

 运行结果

node之http模块_服务器_03

 案例4

const http=require("http")
//创建服务器
http.createServer((req,res)=>{
    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
    res.write(`<html>
        <p>hello geyao</p>
        <div>大家好</div>
    </html>`)
    res.end()
    
}).listen(3002,()=>{
    console.log("geyao.....")
})

运行结果

node之http模块_网络_04

 案例5

const http = require("http")
//创建服务器
http.createServer((req, res) => {
    console.log(req)
    if (req.url === "/home") {




    }
    res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" })
    res.write(renderHtml(req.url))
    res.end()




}).listen(3002, () => {
    console.log("geyao.....")
})
function renderHtml(url) {
    switch (url) {
        case "/home":
            return `<html>
            <p>hello home</p>
        </html>`;
        case "/list":
            return `<html>
            <p>hello list</p>
        </html>`;
        default:
            return `<html>
            <p>hello 404</p>
        </html>`;




    }




}

运行结果

node之http模块_服务器_05

 案例6

const http = require("http")
//创建服务器
http.createServer((req, res) => {
    console.log(req)
    if (req.url === "/home") {




    }
    res.writeHead(renderStatus(req.url), { "Content-Type": "text/html;charset=utf-8" })
    res.write(renderHtml(req.url))
    res.end()




}).listen(3002, () => {
    console.log("geyao.....")
})
function renderHtml(url) {
    switch (url) {
        case "/home":
            return `<html>
            <p>hello home</p>
        </html>`;
        case "/list":
            return `<html>
            <p>hello list</p>
        </html>`;
        default:
            return `<html>
            <p>hello 404</p>
        </html>`;




    }
}
function renderStatus(url){
    var arr=["/home","/list"]
    return arr.includes(url)?200:404
}

 运行结果

node之http模块_网络_06

node之http模块_服务器_07

node之http模块_服务器_08