์๋์ฐจ ๊ณต์ฅ์ ๊ณต์ ๊ณผ ๋น์ท, ์์ฒญ์ ํ์ํ ๊ธฐ๋ฅ์ ๋ํ๊ฑฐ๋, ๋ฌธ์ ๊ฐ ๋ฐ๊ฒฌ๋ ๊ฒ์ ๋ฐ์ผ๋ก ๊ฑท์ด๋ด๋ ์ญํ
Express์ ํฐ ์ฅ์
Node.js๋ง์ผ๋ก ๊ตฌํํ ์๋ฒ์์๋ ๋ฒ๊ฑฐ๋ก์ธ ์ ์๋ ์์
์ ๋ณด๋ค ์ฝ๊ฒ ์ ์ฉ ๊ฐ๋ฅ
2. ๋ฏธ๋ค์จ์ด๋ฅผ ์ฌ์ฉํ๋ ์ํฉ
(1) POST ์์ฒญ ๋ฑ์ ํฌํจ๋ body(payload)๋ฅผ ๊ตฌ์กฐํํ ๋ (์ฝ๊ฒ ์ป์ด๋ด๊ณ ์ ํ ๋)
Node.js๋ก HTTP ์์ฒญ body๋ฅผ ๋ฐ๋ ์ฝ๋
let body = [ ] ;
request . on ( 'data' , ( chunk ) => {
body . push ( chunk ) ;
} ) . on ( 'end' , ( ) => {
body = Buffer . concat ( body ) . toString ( ) ;
// body ๋ณ์์๋ ๋ฌธ์์ด ํํ๋ก payload๊ฐ ๋ด๊น
// ๋คํธ์ํฌ ์์ chunk๋ฅผ ํฉ์น๊ณ , buffer๋ฅผ ๋ฌธ์์ด๋ก ๋ณํ
} )
body-parser ๋ฏธ๋ค์จ์ด๋ฅผ ์ฌ์ฉํ ์ฝ๋
const bodyParser = require ( 'body-parser' ) ;
const jsonParser = bodyParser . json ( ) ;
// ... ์๋ต
app . post ( '/users' , jsonParser , function ( req , res ) {
} )
Express v4.16.0๋ถํฐ๋ body-parser๋ฅผ ์ค์นํ์ง ์๊ณ ๋ด์ฅ ๋ฏธ๋ค์จ์ด์ธ express.json() ์ฌ์ฉ
const jsonParser = express . json ( ) ;
// ... ์๋ต
app . post ( '/api/users' , jsonParser , function ( req , res ) {
} )
express.json() ๋ฏธ๋ค์จ์ด ์ฌ์ฉ์ ์๋ฌ๊ฐ ๋๋ค๋ฉด? โ options์ {strict: false}๋ฅผ ์ถ๊ฐ
const jsonParser = express . json ( { strict : false } ) ;
// ... ์๋ต
app . post ( '/api/users' , jsonParser , function ( req , res ) {
} )
(2) ๋ชจ๋ ์์ฒญ/์๋ต์ CORS ํค๋๋ฅผ ๋ถ์ฌ์ผ ํ ๋
Node.js์ CORS๋ฅผ ์ ์ฉํ๊ธฐ
// ๋ผ์ฐํ
๋ง๋ค ํค๋๋ฅผ ๋ฃ์ด์ฃผ์ด์ผ ํจ
const defaultCorsHeader = {
'Access-Control-Allow-Origin' : '*' ,
'Access-Control-Allow-Methods' : 'GET, POST, PUT, DELETE, OPTIONS' ,
'Access-Control-Allow-Headers' : 'Content-Type, Accept' ,
'Access-Control-Max-Age' : 10
} ;
// ... ์๋ต
// OPTIONS ๋ฉ์๋์ ๋ํ ๋ผ์ฐํ
๋ ๋ฐ๋ก ๊ตฌํํด์ผ ํจ
if ( req . method === 'OPTIONS' ) {
res . writeHead ( 200 , deaultCorsHeader ) ;
res . end ( )
}
cors ๋ฏธ๋ค์จ์ด ์ฌ์ฉ: ๋ชจ๋ ์์ฒญ์ CORS ํ์ฉ
cons cors = require ( 'cors' ) ;
// ... ์๋ต
app . use ( cors ( ) ) ;
cors ๋ฏธ๋ค์จ์ด ์ฌ์ฉ: ํน์ ์์ฒญ์ CORS ํ์ฉ
const cors = require ( 'cors' )
// ... ์๋ต
app . get ( '/products/:id' , cors ( ) , function ( req , res , next ) {
res . json ( { msg : 'This is CORS-enabled for a Single Route' } )
} )
(3) ๋ชจ๋ ์์ฒญ์ ๋ํด url์ด๋ ๋ฉ์๋๋ฅผ ํ์ธํ ๋
use ๋ฉ์๋๋ก ๋ชจ๋ ์์ฒญ์ ๋ํด ๋ฏธ๋ค์จ์ด ์ ์ฉ
const express = require ( 'express' ) ;
const app = express ( ) ;
const myLogger = function ( req , res , next ) {
console . log ( 'LOGGED' ) ;
next ( ) ;
} ;
app . use ( myLogger ) ;
app . get ( '/' , function ( req , res ) {
res . send ( 'Hello World' ) ;
} ) ;
app . listen ( 3000 ) ;
(4) ์์ฒญ ํค๋์ ์ฌ์ฉ์ ์ธ์ฆ ์ ๋ณด๊ฐ ๋ด๊ฒจ์๋์ง ํ์ธํ ๋
HTTP ์์ฒญ์ ํ ํฐ์ด ์๋์ง ํ๋จํ์ฌ, ์ด๋ฏธ ๋ก๊ทธ์ธํ ์ฌ์ฉ์์ผ ๊ฒฝ์ฐ ์ฑ๊ณต, ์๋ ๊ฒฝ์ฐ ์๋ฌ
app . use ( ( req , res , next ) => {
// ํ ํฐ์ด ์๋์ง ํ์ธ
if ( req . headers . token ) {
req . isLoggedIn = true ;
next ( ) ;
} else {
res . status ( 400 ) . send ( 'invalid users' )
}
} )