Super Kawaii Cute Cat Kaoani
본문 바로가기
🏃‍♀️ 대외활동/Codeit Boost-Node.js

9주차 스터디 Express 핵심 기능 [코드잇 부스트 백엔드 스터디 ]

by wonee1 2024. 7. 31.
728x90

 

 

1. express란?

 

💡 Express는 Node.js로 웹서버를 만들 때 사용할 수 있는 프레임워크
     웹서버를 만들 때 필요한 기본적인 기능 제공

 

 

Express 구성요소

🔹미들웨어

🔹리퀘스트 리스폰스 객체

🔹라우터

🔹에러 핸들러

🔹파일

 

 

 


 

 

 

 

2. 미들웨어

 

 

미들웨어란?

 

 

 

 

미들웨어란?

🔹리퀘스트와 리스폰스 사이에 위치하여 어떠한 동작을 하는 함수

🔹Express를 미들웨어의 집합이라고도 부른다

 

***리퀘스트를 받고 리스폰스를 보내는 것이 웹 기본 동작

 

 

클라이언트로부터 리퀘스트를 받아서 리스폰스를 만들어 전달

 

 

미들웨어의 구조

 

function greeting(req,res){
  console.log(req);
   res.json({message:'안녕, 코드잇 (;'});
}//이름이 있는 함수로 만들 수도 있다

파라미터가 2개인 경우

🔹가장 기본적인 미들웨어 구조

 

function greeting(req,res, next){
  next();
   res.json({message:'안녕, 코드잇 (;'});
}

파라미터가 3개인 경우

🔹 next는 다음 미들웨어 함수를 가리킨다

➕ 추가적인 에러 핸들링을 위해 다음 에러 핸들러로 처리를 넘기는 역할을 하기도 한다

 

 

function greeting(err,req,res, next){

   res.json({message:'안녕, 코드잇 (;'});
}

파라미터가 4개인 경우

🔹err는 에러에 대한 정보가 담겨있다

🔹 일반적인 방법으로는 실행이 안된다→ throw나 next(err)로 실행

 

 

 

 

 

미들웨어의 사용법 

 

 

💡미들웨어의 사용법 (1)

다음 미들웨어가 되는 기준

→ 아규먼트로 넘겨준 순서에 따라 다음 미들웨어가 결정된다

 

app.get('/hello',meeting,waving, greeting);
import express from 'express';

const app = express();

//app.get('/', (req, res) => {
 // res.json({ message: '안녕, 코드잇 (;' });
//});//콜백함수가 미들웨어 역할을 하고 있다 (리퀘스트 핸들러)

function meeting(req,res,next){
  console.log('오!');
  next();
}

function waving(req, res, next){
  console.log('(손을 흔들다.)');
  next();
}

function greeting(req,res,next){
   console.log('안녕!');
   res.json({message:'안녕, 코드잇 (;'});
}//이름이 있는 함수로 만들 수도 있다

app.get('/',greeting);
app.get('/hello',meeting, waving, greeting);

//app.METHOD(path, callback[, callback, ...])

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

 

 

💡미들웨어의 사용법 (2)

특정 경로에 http 관계 없이 같은 동작을 실행하도록할 때 all 메소드를 활용한다

import express from 'express';

const app = express();

//app.get('/', (req, res) => {
 // res.json({ message: '안녕, 코드잇 (;' });
//});//콜백함수가 미들웨어 역할을 하고 있다 (리퀘스트 핸들러)

app.all('/hello',(req,res,next)=>{
  console.log('안녕,all!');
  next();
})

app.get('/hello',(req,res,next)=>{
  console.log('안녕,GET!');
  res.json({message:'안녕, 코드잇 (;'});
});

app.post('/hello',(req,res,next)=>{
  console.log('안녕,POST!');
  res.json({message:'안녕, 코드잇 (;'});
});

//app.METHOD(path, callback[, callback, ...])

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

 

 

 

 

use 메소드

🔹 all 메소드와 비슷한 역할을 한다

🔹 모든 리퀘스트가 지정 라우터를 거쳐가도록 할 수 있다

import express from 'express';

const app = express();

//app.get('/', (req, res) => {
 // res.json({ message: '안녕, 코드잇 (;' });
//});//콜백함수가 미들웨어 역할을 하고 있다 (리퀘스트 핸들러)

app.use('/hello',(req,res,next)=>{
  console.log('안녕, use!');
  next();
}) -> hello로 시작하는 모든 경로, 라우터에 대응된다 

app.all('/hello/all',(req,res,next)=>{
  console.log('안녕,all!');
  next();
})

app.get('/hello/all',(req,res,next)=>{
  console.log('안녕,GET!');
  res.json({message:'안녕, 코드잇 (;'});
});

app.post('/hello/all',(req,res,next)=>{
  console.log('안녕,POST!');
  res.json({message:'안녕, 코드잇 (;'});
});

//app.METHOD(path, callback[, callback, ...])

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

 

 

 

 

미들웨어로 req,res 다루기

 

리퀘스트와 리스폰스는 객체이기 때문에 원하는 값을 채울 수 있다

import express from 'express';

const app = express();

function one(req, res, next) {
  console.log(req.query);
  return next();
}

function two(req, res, next) {
  console.log(req.query);
  return next();
}

function three(req, res, next) {
  console.log(req.query);
  return res.json({ message: '안녕, 코드잇 (;' });
}

app.get('/hello', one, two, three);

function authentication(req, res, next){
  req.user="Codeit";
  next();
}

app.get('/me', authentication,(req,res,next)=>{
  console.log(req.uesr);
  res.json({user: req.user});
});

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

 

 

 

에러 처리하기

 

 

 

🔹Express는 기본적인 에러 핸들러가 내장되어있다

🔹기본적으로 html로 에러를 전달한다 → json으로 바꾸려면 따로 작성해줘야한다

 

import express from 'express';

const app = express();

function error(req, res, next) {
  throw new Error('에러 발생!');
  next(new Error('에러 발생!'));
  next();
}

function ok(req, res, next) {
  res.json({ message: 'OK!' });
}

app.get('/error', error, ok);
app.use((err, req, res,next)=>{
  console.log(err);
  res.json({message:'에러 핸들러!'});
});

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

 

 

내장 미들웨어

 

Express는 미리 포함되어있는 미들웨어가 있다 → 내장 미들웨어

🔹모든 경로에 대한 리퀘스트와 리스폰스에 대해 동작하는 것이 목적!

(경로를 생략하는 경우가 많다)

 

 

express.json()

🔹리퀘스트 바디에 있는 json을 객체로 불러오기 위해 사용한다

🔹실행결과로 함수 자체를 반환하다

💡리퀘스트 바디의 내용을 req 객체의 body 속성을 통해서 가져올 때 사용한다 req 객체의 body 속성에 리퀘스트 바디의 값을 객체로 담는 역할

 

import express from 'express';

const app = express();

app.use(express.json());
//app.use((req, res,next)=>{...})
app.post('/products', (req, res) => {
  console.log(req.body);
  res.json({ message: 'Product 추가하기' });
});

app.post('/users', (req, res) => {
  console.log(req.body);
  res.json({ message: 'User 추가하기' });
})

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

 

 

 

express.urlencoded()

🔹contente type이 application/x-www-form-urlencoded인 리퀘스트를 처리하기 위해 사용한다

🔹주로 html의 입력폼을 통해 서버로 데이터를 전송할 때 사용한다)

app.use(express.urlencoded({extended:true}));

 

 

 

express.static()

🔹서버의 파일을 서버 외부를 전달하기 위해 사용한다

app.use(express.static('public')); //파일의 디렉토리 위치를 괄호에 적는다 

 

 

 

ex) JSON 포멧의 리퀘스트 바디를 받아서, 201 Created 상태 코드와 함께 title과 content의 값을 그대로 반환하도록 하는 코드

import express from 'express';

const app = express();

app.use(express.json());

app.post('/posts', (req, res) => {
const { title, content } = req.body;
res.status(201).json({ title, content });
});

app.listen(3000, () => {
console.log('Server is listening on port 3000');
});

 

 

서드파티 미들웨어

 

🔹cookie-parser

리퀘스트로 전달받은 쿠키를 쉽게 파싱할 수 있게 하는 미들웨어

 

🔹morgan

서버로 들어온 리퀘스트를 로그로 남기는 미들웨어

 

🔹cors

CORS는 Cross-Origin Resource Sharing의 약자

웹 사이트가 다른 도메인에 있는 리소스에 접근할 수 있도록 브라우저에서 HTTP 헤더를 통해 제어하는 것

 

🔹multer

Content-Type이 multipart/form-data인 리퀘스트를 간편하게 다룰 수 있는 미들웨어

여기서 multipart/form-data는 입력 폼을 작성하고 전송할 때, 다양한 타입의 데이터를 전송 가능하게 하는 타입

multipart/form-data 타입으로 전달받은 데이터를 리퀘스트 객체에서 사용할 수 있도록한다

 

 


 

3. 라우터

 

라우트 중복 제거하기

 

각 경로마다 라우터가 생겨나면 코드가 복잡해진다

→ 따라서 중복된 경로의 라우터를 제거해준다

app.route('/products')
  .get((req, res)=>{
    res.json({message:'Product 목록 보기'});
  })
  .post((req, res) => {
    res.json({ message: 'Product 추가하기' });
  })

🔹 app.route를 사용해서 중복된 경로의 라우터를 제거할 수 있다

 

 

 

 

라우터 생성

 

const productRouter =express.Router();//라우터 생성 

productRouter.route('/products')
  .get((req, res) => {
    res.json({ message: 'Product 목록 보기' });
  })
  .post((req, res) => {
    res.json({ message: 'Product 추가하기' });
  });

productRouter.route('/products/:id')
  .patch((req, res) => {
    res.json({ message: 'Product 수정하기' });
  })
  .delete((req, res) => {
    res.json({ message: 'Product 삭제하기' });
  });

 

 

라우터 레벨 미들웨어

 

 

특정 라우터 그룹인 라우터에만 적용되는 것을 라우터 레벨 미들웨어라고 한다

 

import express from 'express';

const app = express();

const productRouter = express.Router();

productRouter.unsubscribe((req,res,next)=>{
  console.log('Product Router에서 항상 실행!');
  next();
})

productRouter.route('/')
  .get((req, res) => {
    res.json({ message: 'Product 목록 보기' });
  })
  .post((req, res) => {
    res.json({ message: 'Product 추가하기' });
  });

productRouter.route('/:id')
  .patch((req, res) => {
    res.json({ message: 'Product 수정하기' });
  })
  .delete((req, res) => {
    res.json({ message: 'Product 삭제하기' });
  });

const userRouter =express.Router();

userRouter.get('/',(req,res,next)=>{
  res.json({message: 'User 목록 보기'});
});

app.use('/products', productRouter);
app.use('/users',userRouter)

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

 

 

Express 프로젝트 구조와 모듈화

router와 미들웨어를 각각 파일로 분리한다

 

 

728x90