http 模块
http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的 http.createServer() 方法,就能方便的把一台普通的电脑,变成一台 Web 服务器,从而对外提供 Web 资源服务。
服务器和普通电脑的区别在于,服务器上安装了 web 服务器软件,例如:IIS、Apache 等。通过安装这些服务器软件,就能把一台普通的电脑变成一台 web 服务器。
在 Node.js 中,我们不需要使用 IIS、Apache 等这些第三方 web 服务器软件。因为我们可以基于 Node.js 提供的 http 模块,通过几行简单的代码,就能轻松的手写一个服务器软件,从而对外提供 web 服务。
案例1:创建基本的web服务器
1 2 3 4 5 6 7 8 9 10 11 12
| const http = require('http')
const server = http.createServer()
server.on('request', function (req, res) { console.log('Someone visit our web server.') })
server.listen(8080, function () { console.log('server running at http://127.0.0.1:8080') })
|
案例2:req请求对象和res响应对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const http = require('http') const server = http.createServer()
server.on('request', (req, res) => { const url = req.url const method = req.method const str = `Your request url is ${url}, and request method is ${method}` console.log(str) res.end(str) }) server.listen(80, () => { console.log('server running at http://127.0.0.1') })
|
案例3:解决中文乱码问题
当调用 res.end() 方法,向客户端发送中文内容的时候,会出现乱码问题,此时,需要手动设置内容的编码格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const http = require('http') const server = http.createServer()
server.on('request', (req, res) => { const str = `您请求的 URL 地址是 ${req.url},请求的 method 类型为 ${req.method}` res.setHeader('Content-Type', 'text/html; charset=utf-8') res.end(str) })
server.listen(80, () => { console.log('server running at http://127.0.0.1') })
|
案例4:根据不同的 url 响应不同的 html 内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| const http = require('http') const server = http.createServer()
server.on('request', (req, res) => { const url = req.url; let content = '<h1>404 Not found!</h1>' if (url === '/' || url === '/index.html') { content = '<h1>首页</h1>' } else if (url === '/about.html') { content = '<h1>关于页面</h1>' } res.setHeader('Content-Type', 'text/html; charset=utf-8') res.end(content) })
server.listen(80, () => { console.log('server running at http://127.0.0.1') })
|
案例5: 实现 clock 时钟的 web 服务器
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 33 34 35 36 37 38 39 40 41
| const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer();
server.on('request', (req, res) => { const url = req.url; let fpath = '' if (url === '/') { fpath = path.join(__dirname, './clock/index.html'); } else { fpath = path.join(__dirname, '/clock', url); };
fs.readFile(fpath, 'utf8', (err, dataStr) => { if (err) return res.end('404 Not found.'); res.end(dataStr); }) })
server.listen(80, () => { console.log('server running at http://127.0.0.1'); })
|