响应完整的页面信息

Node.js————响应完整的页面信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const http = require('http')
const path = require('path')
const fs = require('fs')
//封装readFile方法:根据路径读取文件的内容,并且响应到浏览器端
let readFile = (url, response) => {
    fs.readFile(path.join(__dirname, url), 'utf8', (err, fileContent) => {
        if(err){
            response.end('server error')
        }else{
            response.end(fileContent)
        }
    })
}
http.createServer((request, response) => {
    //处理路径的分发
    if(request.url.startsWith("/index")){
        //调用上面封装好的readFile方法
        readFile('index.html', response)
    }else if(request.url.startsWith("/about")){
        readFile('about.html', response)
    }else if(request.url.startsWith("/list")){
        readFile('list.html', response)
    }else{
        //设置响应类型和编码
        response.writeHead(200, {
            'Content-Type': 'text/plain; charset=utf8'
        })
        response.end('你访问的页面正在大西洋漂着...')
    }
}).listen(3000,'192.168.1.105', () => {
    console.log('running...')
})


-->