创建 http 服务器,实现基于http协议的网络通信
如何创建 http 服务器?
如何处理 http 请求?
如何处理 http 响应?
const http = require('http')
const url = require('node:url')
const qs = require('node:querystring')
//创建一个对象
const userInfo = {}
//创建服务
const server = http.createServer((req, res) => {
const { pathname, query } = url.parse(req.url) //获取get请求的参数
//监听GET接口
if (pathname === '/list' && req.method === 'GET') {
const { name, age } = qs.parse(query)
userInfo.name = name
userInfo.age = age
res.end(JSON.stringify({ code: 200, data: { userInfo }, msg: 'success' }))
}
//监听POST接口
if (pathname === '/update' && req.method === 'POST') {
let str = ''
req.on('data', (chunk) => {
str += chunk
})
req.on('end', () => {
const { name, age } = JSON.parse(str)
userInfo.name = name
userInfo.age = age
//设置header信息
res.setHeader('User-Age', 18)
res.writeHead(201, 'okk', { 'User-Name': 'coder-monkey' })
res.end(JSON.stringify({ code: 200, data: { userInfo }, msg: 'success' }))
})
}
})
//开启服务
server.listen(9000, () => {
console.log('server start')
})