NodeJs 内置模块 http 介绍

创建 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')
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值