Node.js处理HTTP
Pcjmy2022-06-05JavaScriptNode.js
Node.js处理HTTP
req 和 res
监听HTTP请求
const http = require('http')
const server = http.createServer(() => {
console.log('已经收到 http 请求')
})
server.listen(3000)
console.log('http请求已经被监听')
获取和使用
const server = http.createServer((req, res) => {
const url = req.url
console.log('url is: ', url)
res.end('Hello World!')
})
路由
路由包含什么
- method,如GET、POST
- url规则,如/api/list和/api/create
- 输入(Request body)和输出(Response body)格式
定义GET
和POST
路由
const server = http.createServer((req, res) => {
const url = req.url
const path = url.split('?')[0]
const method = req.method
console.log('method is:', method)
// 定义GET路由
if (path === '/api/get' && method === 'GET') {
res.end('this is get router')
}
// 定义POST路由
if (path === '/api/post' && method === 'POST') {
res.end('this is post router')
}
res.end('404')
})
querystring
querystring是URL的一部分,其中包含着需要传给web application的数据。
querystring是动态网页的基石(web1.0 -> web2.0)
如何利用querystring实现动态网页
- 服务端拿到querystring
- 根据不同的querystring,返回不同的内容
- 即变化 querystring,就是变换内容(只要服务端支持)
querystring的使用
const server = http.createServer((req, res) => {
const url = req.url
const path = url.split('?')[0]
const queryStr = url.split('?')[1]
const method = req.method
// 解析querystring
const query = {}
queryStr && queryStr.split('&').forEach(item => {
const key = item.split('=')[0]
const val = item.split('=')[1]
query[key] = val;
})
console.log('query is', query)
res.end('404')
})
# 使用API
const querystring = require('querystring')
const server = http.createServer((req, res) => {
const url = req.url
const path = url.split('?')[0]
const queryStr = url.split('?')[1]
const method = req.method
const query = querystring.parse(queryStr)
console.log('query is', query)
res.end('404')
})
注意
hash不能让服务端获取
结构化与非结构化
- 结构化的数据,易于通过程序访问和分析,如对象和数组
- 非结构化的数据,不易通过程序分析,如字符串
- 编程中的数据,都尽量结构化
res返回数据
返回JSON格式
if (path === '/api/list' && method === 'GET') {
// 返回结果
const result = {
errno: 0,
data: [
{ user: '张三', content: '留言1' },
{ user: '李四', content: '留言2' }
]
}
res.writeHead(200, { 'Content-type': 'application/json'})
res.end(JSON.stringify(result))
}
if (path === '/api/create' && method === 'POST') {
const result = {
errno: 0,
message: '创建成功'
}
res.writeHead(200, { 'Content-type': 'application/json'})
res.end(JSON.stringify(result))
}
res.writeHead(404, { 'Content-type': 'text/plain' })
res.end('404 Not Found')
返回HTML格式
如何返回HTML
- Content-type: text/html
- res.end(...)
- 浏览器会根据Content-type识别出html格式
res.writeHead(404, { 'Content-type': 'text/html' })
res.end(`
<!DOCTYPE html>
<html>
<head>
<title>404</title>
</head>
<body>
<h1>404 Not Found</h1>
</body>
</html>
`)
接收requestbody
浏览器能接收流(stream)数据
- 服务端res.end(...),会自动以流的形式返回
- 浏览器会识别到流,并持续接收信息(会有进度条)
- 待全部接收完,再做显示或处理(视频是一段一段的播放)
服务端接收流(stream)数据
if (path === '/api/create' && method === 'POST') {
console.log('req content-type', req.headers['content-type'])
let bodyStr = ''
req.on('data', chunk=>{
bodyStr = bodyStr + chunk.toString()
})
req.on('end', ()=>{
const body = JSON.parse(bodyStr)
console.log('body is', body)
res.end('接收完成')
})
return
}