node.js如何搭建HTTP服务

进入终端,首先执行

npm init -y

初始化环境,然后在【index.js】文件中编写下述代码

const http = require('http')
const querystring = require('querystring')

const server = http.createServer((req, res) => {
    const method = req.method
    const url = req.url
    const path = url.split('?')[0]
    const query = querystring.parse(url.split('?')[1])
    //设置返回格式为JSON,很重要
    res.setHeader('Content-type', 'application/json')
    const resData = {
        method,
        url,
        path,
        query
    }
    //返回
    if (method === 'GET') {
        res.end(JSON.stringify(resData))
    }
    if (req.method === 'POST') {
        //接收数据
        let postData = ''
        req.on('data', chunk => {
            postData += chunk.toString()
        })
        req.on('end', () => {
            resData.postData=postData
            // 返回
            res.end(JSON.stringify(resData))
        })
    }
})
server.listen(8000, () => {
    console.log('listening on 8000 prot')
})

之后使用下述命令启动本地服务器

node index.js

之后在浏览器地址栏输入
【http://localhost:8000/blog/list?author=lt&keyword=a】验证get请求
网页返回下图
网页返回图片
控制栏中返回下图
在这里插入图片描述
使用postman验证post请求,输入下述信息
在这里插入图片描述
点击post按钮后返回如下结果
在这里插入图片描述
最后在终端使用快捷键 【control+c】 终止服务

发布了34 篇原创文章 · 获赞 4 · 访问量 2189

猜你喜欢

转载自blog.csdn.net/qq_41629800/article/details/105097482