原生nodejs搭建Web服务器
1 创建 Web 服务器
- 创建服务器
app = http.createServer()
- 监听请求
app.on('request', (req, res) => {}
,req 为接收的请求信息,res 为发送的响应信息
- 监听端口
app.listen(3000)
- 解析 url
url.parse(req.url, true)
- 路由转发
- 返回响应
res.end()
创建服务器、监听请求、监听端口可简写为:
1
| http.createServer((req, res) => {}).listen(3000)
|
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 42
| const http = require('http')
const url = require('url')
const app = http.createServer()
app.on('request', (req, res) => { console.log(req.method.toLowerCase())
console.log(req.url)
console.log(req.headers['accept'])
res.writeHead(200, { 'content-type': 'text/html;charset=utf8', })
console.log(req.url) let { query, pathname } = url.parse(req.url, true) console.log(query.name) console.log(query.age)
if (pathname === '/index' || pathname === '/') { res.end('<h2>欢迎来到首页</h2>') } else if (pathname === '/list') { res.end('welcome to listpage') } else { res.end('not found') } })
app.listen(3000) console.log('网站服务器启动成功')
|
2 post 请求
- querystring 模块解析 post 请求主体
querystring.parse()
- post 主体信息分批抵达服务器,data 事件监听每批到达数据,end 事件监听数据传输完毕事件
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
| const http = require('http')
const app = http.createServer()
const querystring = require('querystring')
app.on('request', (req, res) => {
let postParams = ''
req.on('data', (params) => { postParams += params })
req.on('end', () => { console.log(querystring.parse(postParams)) })
res.end('ok') })
app.listen(3000) console.log('网站服务器启动成功')
|
3 请求静态资源
- fs 模块获取资源位置
- mime 模块用于根据请求资源后缀名自动获取 content-type
- path 模块连接路径
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 42
| const http = require('http') const url = require('url') const path = require('path') const fs = require('fs')
const mime = require('mime')
const app = http.createServer()
app.on('request', (req, res) => { let pathname = url.parse(req.url).pathname
pathname = pathname === '/' ? '/default.html' : pathname
let realPath = path.join(__dirname, 'public' + pathname)
let type = mime.getType(realPath)
fs.readFile(realPath, (error, result) => { if (error != null) { res.writeHead(404, { 'content-type': 'text/html;charset=utf8', }) res.end('文件读取失败') return }
res.writeHead(200, { 'content-type': type, })
res.end(result) }) })
app.listen(3000) console.log('服务器启动成功')
|
最后更新时间:
转载请注明出处