IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Node.js基础入门—2 -> 正文阅读

[网络协议]Node.js基础入门—2

nodejs处理http请求

一、Request(req)、Response(res)

在这里插入图片描述
在这里插入图片描述

const http = require('http')

// req Request,res Response
const server = http.createServer((req, res) => {
    // console.log('已经收到 http 请求')
    const url = req.url // http://localhost:3000/index.html
    console.log('url is: ', url) // /index.html
    res.end('hello world') // res 返回信息给前端
})

server.listen(3000) // 可以监听 http 请求
console.log('http 请求已经被监听,3000 端口, 请访问 http://localhost:3000')

二、定义路由

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、querystring

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

// req Request,res Response
const server = http.createServer((req, res) => {
    const url = req.url // favicon.ico
    const path = url.split('?')[0] // /api/list
    const queryStr = url.split('?')[1] // 'a=100&b=200' 非结构化
    const method = req.method

    // console.log('url is: ', url) // /api/list?a=100&b=200
    // console.log('method is: ', method)

    // 解析 querystring
    // const query = {}
    // queryStr && queryStr.split('&').forEach(item => {
    //     // item 即 a=100 形式
    //     const key = item.split('=')[0] // 'a'
    //     const val = item.split('=')[1] // '100'
    //     query[key] = val // { a: '100', b: '200' } 结构化
    // })
    const query = querystring.parse(queryStr)
    console.log('query is ', query)

    // 定义路由:模拟获取留言板列表
    if (path === '/api/list' && method === 'GET') {
        if (query.filterType === '1') {
            res.end('this is list router, all')
        }
        if (query.filterType === '2') {
            res.end('this is list router, only mine')
        }
        // res.end('this is list router') // res 的返回,后面会讲
    }
    
    // 定义路由:模拟创建留言
    if (path === '/api/create' && method === 'POST') {
        res.end('this is create router')
    }

    res.end('404')
})

server.listen(3000) // 可以监听 http 请求
console.log('http 请求已经被监听,3000 端口, 请访问 http://localhost:3000')

在这里插入图片描述

四、res返回数据

在这里插入图片描述
在这里插入图片描述

五、获取req body

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

// req Request,res Response
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)

    // 定义路由:模拟获取留言板列表
    if (path === '/api/list' && method === 'GET') {
        // res.end('this is list router')

        // 返回结果
        const result = {
            errno: 0,
            data: [
                { user: '张三', content: '留言1' },
                { user: '李四', content: '留言2' }
            ]
        }
        res.writeHead(200, { 'Content-type': 'application/json' })
        res.end( JSON.stringify(result) ) // body
    }
    
    // 定义路由:模拟创建留言
    if (path === '/api/create' && method === 'POST') {
        // res.end('this is create router')

        const reqType = req.headers['content-type']

        let bodyStr = ''
        req.on('data', chunk => { // 服务端怎么去识别“流”,并接收数据
            // chunk 即“流”的每一段数据
            bodyStr = bodyStr + chunk.toString()
        })
        req.on('end', () => { // 服务端怎么知道流完了
            if (reqType === 'application/json') { // json 格式
                const body = JSON.parse(bodyStr)
                console.log('body is ', body) // 对象格式
            }
            
            res.end('接收完成') // 异步
        })

        // const result = {
        //     errno: 0,
        //     message: '创建成功'
        // }
        // res.writeHead(200, { 'Content-type': 'application/json' })
        // res.end( JSON.stringify(result) ) // body

        return
    }

    // 没有命中路由,默认 404
    // res.end('404')
    // res.writeHead(404, { 'Content-type': 'text/plain' })
    // res.end('404 Not Found')
    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>
    `)
})

server.listen(3000) // 可以监听 http 请求
console.log('http 请求已经被监听,3000 端口, 请访问 http://localhost:3000')

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-09-12 20:46:44  更:2021-09-12 20:46:56 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年6日历 -2024/6/27 1:59:44-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码