๐ŸŒฑ → ๐ŸŒณ

middleware๋ž€? ๋ณธ๋ฌธ

Server

middleware๋ž€?

BAY 2022. 9. 2. 18:00
728x90

๐Ÿ“Œ middleware๋ž€?

  • (์‚ฌ์ „์ ์˜๋ฏธ) ์„œ๋กœ ๋‹ค๋ฅธ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜(ํ”„๋กœ๊ทธ๋žจ)์ด ์„œ๋กœ ํ†ต์‹ ์„ ํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋˜๋Š” ์†Œํ”„ํŠธ์›จ์–ด
  • ์ฆ‰, ์–‘์ชฝ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ฐ€์šด๋ฐ์—์„œ ์—ญํ• ์„ ํ•˜๋Š” ์†Œํ”„ํŠธ์›จ์–ด
  • Express: ๋ฒก์—”๋“œ ์„œ๋น„์Šค ๊ตฌ์„ฑ์„ ์œ„ํ•œ ๋‹ค์–‘ํ•œ ์ƒํ™ฉ์— ๋งž๋Š” ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์„œ๋น„์Šค๋ฅผ ๋ฏธ๋“ค์›จ์–ด ํ˜•ํƒœ๋กœ ์ œ๊ณต
  • Express ์—์„œ์˜ ๋ฏธ๋“ค์›จ์–ด๋Š” ์„œ๋ฒ„์— ๋“ค์–ด์˜จ ์š”์ฒญ์ด ๋“ค์–ด์™€์„œ ์‘๋‹ต์œผ๋กœ ๋‚˜๊ฐˆ ๋•Œ ๊นŒ์ง€ ๊ฑฐ์น˜๋Š” ๋ชจ๋“  ํ•จ์ˆ˜ ๋˜๋Š” ๊ธฐ๋Šฅ์„ ์˜๋ฏธ
    • ์š”์ฒญ -> ๋ฏธ๋“ค์›จ์–ด -> ์‘๋‹ต

 

โœ… middleware ์‚ฌ์šฉํ•˜๊ธฐ 

  • Express ์—์„œ๋Š” app.use ๋˜๋Š” app.method ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ๋ฏธ๋“ค์›จ์–ด ์‚ฌ์šฉ
  • ๊ธฐ์กด์— ํ•จ์ˆ˜๋ฅผ ์„ ์–ธํ•˜์—ฌ ์‚ฌ์šฉํ–ˆ๋˜ ๊ฒƒ ์ฒ˜๋Ÿผ, ์œ„์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ์ด์šฉํ•ด์„œ req, res ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ
app.use(‘์š”์ฒญ ์ฃผ์†Œ‘, (req, res, next) => {});

 

 

๐Ÿ“ next

: callback ํ•จ์ˆ˜๋กœ์„œ ํ•ด๋‹น ํ•จ์ˆ˜๊ฐ€ ํ˜ธ์ถœ ๋˜๋ฉด ํ˜„์žฌ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์ข…๋ฃŒํ•˜๊ณ  ๋‹ค์Œ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์‹คํ–‰

  • next ๋ฅผ ์ƒ์šฉํ•ด์„œ ๋‹ค์Œ ๋ฏธ๋“ค ์›จ์–ด๋ฅผ ์‹คํ–‰ ์‹œํ‚ฌ ๋•Œ, ์ด์ „ ๋ฏธ๋“ค ์›จ์–ด์—์„œ ์ฒ˜๋ฆฌํ•œ ๊ฐ’์„ ์ „๋‹ฌ ํ•˜๊ณ  ์‹ถ์„ ๋•Œ๊ฐ€ ๋ฐœ์ƒ
  • global ์˜์—ญ์—์„œ ๋ณ€์ˆ˜๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“ค์–ด์„œ ์ „๋‹ฌํ•ด๋„ ๋˜์ง€๋งŒ global ๋ณ€์ˆ˜๋Š” ๋ณดํ†ต ์‚ฌ์šฉ์„ ์ž˜ ์•ˆํ•˜๋Š” ๊ฒƒ์ด ์ข‹์Œ
    • ๋ณ€์ˆ˜๊ฐ€ ์–ธ์ œ ์–ด๋””์—์„œ ๋ณ€๊ฒฝ์ด ๋˜์–ด ๋ฌธ์ œ๋ฅผ ๋ฐœ์ƒ ์‹œํ‚ฌ์ง€ ์˜ˆ์ธก์ด ์–ด๋ ต๊ธฐ ๋•Œ๋ฌธ
  • ์ด๋Ÿด ๋•Œ์—๋Š” req ๊ฐ์ฒด์— ํ•„๋“œ๋ฅผ ์ถ”๊ฐ€ํ•ด์„œ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ๋งŽ์ด ์‚ฌ์šฉ๋จ (์•„๋ž˜ ์ฝ”๋“œ ์ฐธ๊ณ )
const express = require('express');
const app = express();
const PORT = 4000;
app.use('/', (req, res, next) => {
  console.log('Middleware 1');
  req.reqTime = new Date();
  next();
});
app.use((req, res, next) => {
  console.log('Middleware 2');
  res.send(`Requsted at ${req.reqTime}`);
});
app.listen(PORT, () => {
  console.log(`The express server is running at port: ${PORT}`);
});

 

๐Ÿ“ Promise

fs๋ฅผ ์ด์šฉํ•˜์—ฌ promise ์ƒํ™ฉ ๋งŒ๋“ค๊ธฐ 

์‚ฌ์šฉ์ด ์ง๊ด€์ ์ธ Async / Await ์„ ์ด์šฉํ•ด์„œ ๊ตฌํ˜„

const express = require('express');
const fs = require('fs');
const app = express();
const PORT = 4000;
app.use('/', async (req, res, next) => {
  console.log('Middleware 1');
  req.reqTime = new Date();
  req.fileContent = await fs.promises.readFile('package.json', 'utf-8');
  next();
});
app.use((req, res, next) => {
  console.log('Middleware 2');
  console.log(req.fileContent);
  res.send(`Requsted at ${req.reqTime}`);
});
app.listen(PORT, () => {
  console.log(`The express server is running at port: ${PORT}`);
});
728x90

'Server' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

REST API๋ž€ ?  (0) 2023.05.31
AWS EC2์— ์ ‘์†ํ•˜๊ธฐ  (0) 2023.05.28
์„œ๋ฒ„๋ž€ ๋ฌด์—‡์ธ๊ฐ€?  (1) 2022.08.25