Nest.js 再探 解析HTTP請求


body-parser

包body-parser屬於express,原型如下:

[Function] {
  json: [Getter], // application/json parser
  raw: [Getter], // application/octet-stream parser
  text: [Getter], // text/plain parser
  urlencoded: [Getter] // application/x-www-form-urlencoded parser
}

body-parser導出一個CommonJS模塊,使用以下方式取得中間件並應用到express:

import bodyParser from 'body-parser';
app.use(bodyParset.json()); // apply application/json parser

import { json } from 'body-parser';
app.use(json());

解析之后,req.body可用。

打印HTTP請求

import { _console } from '@develon/js/lib/node';

_console.hook();
/**
 * 記錄HTTP請求
 * @param req 
 * @param res 
 * @param next 
 */
export default function (req, res, next) {
    let members = [
        `HTTP請求:`, req.method, req.url, req.httpVersion,
        'Headers :>>', req.headers,
    ];
    if (req.method?.match(/^POST$/i)) {
        members.push('Body :>>', req.body);
    }
    console.log(...members);
    next();
};

END


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM