nodejs-原生的post和get请求

9次阅读

共计 755 个字符,预计需要花费 2 分钟才能阅读完成。

把今天学到的东西记录一下

const http = require('http')
// querystring 模块提供用于解析和格式化 URL 查询字符串的实用工具
const querystring = require('querystring')

const server = http.createServer((req, res) => {

    //  请求的方式
    const method = req.method

    // 获取完整请求 url
    const url = req.url

    // url 路径
    const path = url.split('?')[0]

    // 解析  get 请求的参数  为? 后面  所以数组下标为 1
    const getParams = querystring.parse(url.split('?')[1])

    // 设置返回的格式  json 格式
    res.setHeader('Content-type','application/json')

    // 返回的数据
    const resData = {
        method,
        url,
        path,
        getParams
    }

    // 0. 如果是 Post 请求
    if (method === 'POST'){
       
        // 接收数据
        let postData = ''
        // chunk 为一点点数据,逐渐积累
        req.on('data', chunk => {postData += chunk.toString()
        })

        req.on('end', () => {
            resData.postData = postData
            // 在这里返回 因为是异步
            res.end(
                // 返回 json 字字符串
                JSON.stringify(resData)
            )
        })
    }

    // 1. 如果是 get 请求
    if (method === 'GET'){
        // 返回
        res.end(
            // 返回 json 字字符串
            JSON.stringify(resData)
        )
    }

})

server.listen(8000)

正文完
 0