http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。
通过 http 模块提供的 http.createServer() 方法,就能方便的把一台普通的电脑,变成一台 Web 服务器,从而对外提供 Web 资源服务。
创建最基本的web服务器
- 导入http模块
- 创建web服务器实例
- 为服务器实例绑定request事件,监听客户端的请求
- 启动服务器
示例代码
//1.导入http模块
const http = require('http')
//2.创建web服务器实例
const server = http.createServer()
//3.为服务器实例绑定request事件,监听客户端的请求
server.on('request',function(req,res){
console.log('Someone visit our web server')
//获取请求的url地址
const url = req.url
//设置默认的响应内容为404 Not found
let content = '404 Not found'
//判断用户请求的是否为/ 或 /index.html首页
//判断用户请求的是否为/about.html关于页面
if(url === '/' || url==='/index.html'){
content = '<h1>首页</h1>'
}else if(url==='/about.html'){
content = '<h1>关于页面</h1>'
}
//设置Content-Type响应头,防止中文乱码
res.setHeader('Content-Type','text/html;charset=utf-8')
//使用res.end()把内容响应给客户端
res.end(content)
})
//启动服务器
server.listen(8080,function(){
console.log('server running at http://127.0.0.1:8080')
})
应用举例:
本地磁盘上有一个clock文件夹,里面包含了html,css,js文件,html文件在浏览器上打开,显示的是一个时钟的图案。 要求:创建一个web服务器,以clock文件夹里面的内容作为服务器资源,当客户端访问服务器时,输入 /index.html 加载时钟图案。
我本地的文件夹结构如下:
//1.1导入http模块
const http = require('http')
//1.2导入fs模块
const fs = require('fs')
//1.3导入path模块
const path = require('path')
//2.1创建web服务器
const server = http.createServer()
//2.2监听web服务器的request事件
server.on('request',(req,res) => {
// 3.1获取到客户端请求的url地址
// /clock/index.html
// /clock/index.css
// /clock/index.js
const url = req.url
// 3.2 把请求的url地址映射为具体文件的存放路径
let fpath = ''
if (url === '/'){
fpath = path.join(__dirname,'../clock/index.html')
}else{
fpath = path.join(__dirname,'../clock',url)
}
// 4.1 根据映射过来的文件路径读取文件的内容
fs.readFile(fpath,'utf8',(err,dataStr) => {
//4.2 读取失败,向客户端响应固定的"错误消息"
if (err) return res.end('404 Not found')
//4.3 读取文件成功,将读取成功的内容,响应给客户端
res.end(dataStr)
})
})
//2.3启动服务器
server.listen(8080, () => {
console.log('server running at http://127.0.0.1')
})