이 기사의 내용은 Express 미들웨어 바디 파서의 구현 방법에 관한 것입니다. 이는 특정 참고 가치가 있으므로 도움이 될 수 있기를 바랍니다.
이전 글에서는 body-parser 미들웨어를 사용하여 post 요청을 처리하는 방법에 대해 작성했습니다. 오늘은 body-parser에서 urlencoded 메서드를 대략적으로 구현해 보겠습니다.
먼저 명령 프롬프트를 통해 mkdir lib && cd lib를 입력하세요.
touch body-parser.js를 입력하세요.
body-parser.js에 다음 코드를 입력하세요.
// lib/body-parser.js const querystring = require('querystring'); module.exports.urlencoded = function (req, res, next) { let chunks = []; req.on('data', data => { chunks.push(data); }); req.on('end', () => { // 合并Buffer。 let buf = Buffer.concat(chunks).toString(); // 把querystring解析过的json 放到 req.body上。 req.body = querystring.parse(buf); next(); }); }
다음은 주요 프로그램 코드입니다.
// app.js const express = require('express'); const bodyParser = require('./lib/body-parser'); let app = express(); app.use(bodyParser.urlencoded); app.post('/', (req, res) => { res.send(req.body); }); app.listen(8000);
이제 body-parser 미들웨어와 유사한 기능이 완료되었습니다. Req.body가 요청한 게시물 데이터를 갖습니다.
【관련 추천: JavaScript 비디오 튜토리얼】
위 내용은 Express 미들웨어 Body-Parser 구현 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!