라벨이 express인 게시물 표시

[Express.js] 더이상 body-parser를 사용하지 않아도 된다.

body-parser는 유명한 라이브러리이다. 그 이유는 body-parser를 사용하면 클라이언트측에서 보내는 요청과 데이터에 대해서 서버측에서 특정 라우터에서 req.body객체로 데이터를 쉽게 전달 받을 수 있기 때문이다. 사용방법: const express = require ( ' express ' ) ; const bodyParser = require ( ' body-parser ' ) ; const app = express () ; // parse application/x-www-form-urlencoded app . use ( bodyParser . urlencoded ( { extended : true } )) ; // parse application/json app . use ( bodyParser . json ()) ; app . post ( ' /profile ' , ( req , res ) => { console . log ( req . body ) ; } ) ; 만약에 body-parser를 사용하지 않는다면 req.body의 반환값은 undefined가 될 것이다. 그런데!! 이렇게 body-parser를 설치했어야했는데 이제는 더이상 body-parser를 사용하지 않아도 된다. express.js에서 body-parser 기능을 추가했기 때문이다. 참고:  https://expressjs.com/en/4x/api.html#express-json-middleware 앞으로는 body-parser 대신에 아래와 같이 미들웨어를 작성하면 똑같이 req.body 객체로 클라이언트 측에서 보낸 요청과 데이터를 받을 수 있게 되었다. const express = require ( ' express ' ) ; const app = express () ; app . use ( express . json ()) ; app . use ( expres

[Express.js] Route Parameter (동적 Routing ,동적 params)

이미지
Route Parameter 일단 아래 코드에서 라우팅 경로를 보자. app . get ( ' /category/html ' , ( req , res ) => { res . send ( ` hello html~~~~~ ` ) } ) app . get ( ' /category/css ' , ( req , res ) => { res . send ( ` hello css~~~~~ ` ) } ) app . get ( ' /category/javascript ' , ( req , res ) => { res . send ( ` hello javascript~~~~~ ` ) } ) app . get ( ' /category/nodejs ' , ( req , res ) => { res . send ( ` hello nodejs~~~~~ ` ) } ) .... '/category/html'  '/category/css'  '/category/javascript' '/category/nodejs' ... 공통적인 라우팅 경로로 /category 로 작성되어있고 뒤에 카테고리별 각각의 경로가 추가적으로 작성되어있다. 만약에 category 목록이 100개라면 100개에 대한 경로를 위에서 처럼 하드 코딩으로 100개나 적어줘야한다. 이러한 하드 코딩을 없애고 카테고리 목록에 따른 라우팅 주소를 동적으로 받을 수 있게 해주는 방법이 Route Parameter 이다. 위에서 하드코딩된 라우터를 Route Paramter를 통해 변경해 보자. Route Parameter는 아래 코드에서처럼 :categoryId 와 같이 작성해 주면 된다. 원하는 명칭을 : 기호와 함께 작성한다. app . get ( ' /category/:categoryId ' , async ( req , res )