Node.js 实现一个body-parse中间件

24 篇文章 0 订阅
13 篇文章 0 订阅
本文档展示了一个使用Node.js实现的body-parser中间件,用于解析HTTP请求体中的application/x-www-form-urlencoded、application/json和text/plain类型的数据。在server.js中,这个中间件被用于处理POST请求,并将解析后的请求体发送回客户端。
摘要由CSDN通过智能技术生成

Node.js 实现一个body-parse中间件

bodyParse.js


const fs = require('fs');
const querystring = require('querystring');
const qs = require('qs');

function BodyParser() {

}
// 解析 application/x-www-form-urlencoded 数据
BodyParser.prototype.urlencoded = function (options = {}) {
  const { extended = false } = options;
  return function (req, res, next) {
    const contentType = req.headers['content-type'];
    if (contentType == 'application/x-www-form-urlencoded') {
      const buf = [];
      req.on('data', data => {
        buf.push(data);
      })
      req.on('end', () => {
        const result = Buffer.concat(buf).toString();
        req.body = extended ? qs.parse(result) : querystring.parse(result);
        next();
      })
    } else {
      next();
    }
  }
}
// 解析 application/json 数据
BodyParser.prototype.json = function (options = {}) {
  return function (req, res, next) {
    const contentType = req.headers['content-type'];
    if (contentType == 'application/json') {
      const buf = [];
      req.on('data', data => {
        buf.push(data);
      })
      req.on('end', () => {
        const result = Buffer.concat(buf).toString();
        req.body = JSON.parse(result);
        next();
      })
    } else {
      next();
    }
  }
}
// 解析 text/plain 数据
BodyParser.prototype.text = function (options = {}) {
  return function (req, res, next) {
    const contentType = req.headers['content-type'];
    if (contentType == 'text/plain') {
      const buf = [];
      req.on('data', data => {
        buf.push(data);
      })
      req.on('end', () => {
        const result = Buffer.concat(buf).toString();
        req.body = result;
        next();
      })
    } else {
      next();
    }
  }
}
module.exports = new BodyParser();

server.js


const express = require('express');
const app = express();
// const bodyParser = require('body-parser'); // body-parse 中间件
const bodyParser = require('./bodyParser');  // 自己写的body-parse

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.text());

app.post('/user', (req, res) => {
  const body = req.body;
  res.send(body);
})

app.listen(3000, () => console.log('server running at http://localhost:3000'));

test.js


const http = require('http');
const iconv = require('iconv-lite');
//发送时必须附带Content-Type请求头
const options = {
  host: 'localhost',
  port: 3000,
  method: 'POST',
  path: '/user',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
    // 'Content-Type': 'application/json'
    // 'Content-Type': 'text/plain'
  }
}
// 用node http模块进行请求.
const request = http.request(options, response => {
	// 将response返回的数据通过pipe管道输出到控制台
  response.pipe(process.stdout);
})

request.end('name=huzhixin&age=20');
// request.end('{"name":"huzhixin","age":20}');
// request.end('胡志欣');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值