Skip to content

Latest commit

 

History

History
57 lines (40 loc) · 1.08 KB

9.md

File metadata and controls

57 lines (40 loc) · 1.08 KB

实现clock时钟的web服务器

[toc]

需要模块

const http = require('http')
const fs = require('fs')
const path = require('path')
//path模块用来处理路径

实现

const http = require('http')
const fs = require('fs')
const path = require('path')

//创建web服务器
const server = http.createServer()

//监听web服务器
server.on('request', (req, res) => {
    

//1. 获取请求的url地址,和客户端有关使用req获取
const url = req.url

//2.设置响应内容为404 not found
let content = '<h1>404 not found</h1>'

//把请求的url地址映射为具体文件的存放路径
const fpath = path.join(__dirname,url)

//读取文件
fs.readFile(fpath,`utf8`,(err,dataStr) =>{
    if(err) return res.end('404 Not found')
    //读取成功
    res.end(dataStr)
})
//5.设置content-type响应头,防止中文乱码
res.setHeader('Content-Type','text/html;charset=utf-8')

//6.使用res.end()把相应内容给客户端
res.end(content)
})    

//启动服务器
server.listen(80, () => {
    console.log('server runing ar http:https://127.0.0.1')
})