[Nodejs] 12. 接收request body-----代码演示

  1. 服务端识别“流”
let bodyStr = '';
        req.on('data', chunk => {                           // 服务端怎么去识别流,并接收数据
            // chunk为流的每一段数据
            bodyStr = bodyStr + chunk.toString();
        });
  1. 服务端识别流的完成
req.on('end', () => {                               // 服务端怎么知道流完了
            console.log('bodyStr is', bodyStr)
            res.end('接收完成');

        })
  1. 完整代码:从模拟创建留言之后看
const http = require('http');
const querystring = require('querystring');

// req: request, res: response
const server = http.createServer((req, res) => {
    const url = req.url;
    const method = req.method
    const path = url.split('?')[0]
    const queryStr = url.split('?')[1]          //a=1&b=2

    // 简化版解析quertStr
    const query = querystring.parse(queryStr)

    // 定义路由,模拟获取留言板列表:访问该路由则返回的内容
    // 返回结果
    const result = {
        errno: 0,
        data:[
            {user:'张三', content: '留言1'},
            {user:'李四', content: '留言2'}
        ]
    }
    if (path === '/api/list' && method === 'GET') {
        res.writeHead(200, {'Content-type': 'application/json'});
        // 为什么要用JSON.stringfy转换成字符串?因为end()里只能接字符串,所以把对象转换成字符串
        res.end(JSON.stringify(result)
        )
    }

    // 定义路由,模拟创建留言
    if (path === '/api/create' && method === 'POST') {
        let bodyStr = '';
        req.on('data', chunk => {                           // 服务端怎么去识别流,并接收数据
            // chunk为流的每一段数据
            bodyStr = bodyStr + chunk.toString();
        });
        req.on('end', () => {                               // 服务端怎么知道流完了
            console.log('bodyStr is', bodyStr)
            res.end('接收完成');

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

server.listen(3000);        // 可以监听http的请求了
console.log('http请求已经被监听,3000端口');
  1. 用POSTMAN模仿前端给服务器发送请求
    在这里插入图片描述
  2. 返回结果
    在这里插入图片描述

在这里插入图片描述
6. 优化:将接收的字符串格式转换成json格式

const body = JSON.parse(bodyStr)                // 转换成json格式
  1. 完整代码如下:
const http = require('http');
const querystring = require('querystring');

// req: request, res: response
const server = http.createServer((req, res) => {
    const url = req.url;
    const method = req.method
    const path = url.split('?')[0]
    const queryStr = url.split('?')[1]          //a=1&b=2

    // 简化版解析quertStr
    const query = querystring.parse(queryStr)

    // 定义路由,模拟获取留言板列表:访问该路由则返回的内容
    // 返回结果
    const result = {
        errno: 0,
        data:[
            {user:'张三', content: '留言1'},
            {user:'李四', content: '留言2'}
        ]
    }
    if (path === '/api/list' && method === 'GET') {
        res.writeHead(200, {'Content-type': 'application/json'});
        // 为什么要用JSON.stringfy转换成字符串?因为end()里只能接字符串,所以把对象转换成字符串
        res.end(JSON.stringify(result)
        )
    }

    // 定义路由,模拟创建留言
    if (path === '/api/create' && method === 'POST') {
        //获取传过来的数据是什么格式
        console.log('req content-type', req.headers['content-type'])
        const reqType = req.headers['content-type'];
        let bodyStr = '';
        req.on('data', chunk => {                           // 服务端怎么去识别流,并接收数据
            // chunk为流的每一段数据
            bodyStr = bodyStr + chunk.toString();
        });
        req.on('end', () => {                               // 服务端怎么知道流完了
            if (reqType === 'application/json') {
                console.log('bodyStr is', bodyStr)              // 字符串格式
                const body = JSON.parse(bodyStr)                // 转换成json格式
                console.log('body is', body)                    // 对象格式
            }
            res.end('接收完成');

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

server.listen(3000);        // 可以监听http的请求了
console.log('http请求已经被监听,3000端口');

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值