[유튜브강의] Smart Lab. 코드기어 NodeJS기초-10.Express 서버 만들기2-미들웨어 > 자유게시판

본문 바로가기
사이트 내 전체검색

자유게시판

[유튜브강의] Smart Lab. 코드기어 NodeJS기초-10.Express 서버 만들기2-미들웨어

페이지 정보

profile_image
작성자 로봇
댓글 0건 조회 362회 작성일 25-02-15 07:23

본문

// NodeJS기초-10.Express 서버 만들기2-미들웨어

const express = require('express');
const app = express();
var router = express.Router(); // express.Router()를 사용하면 라우터 레벨의 미들웨어를 사용할 수 있습니다.
app.listen(3000);

// 한개의 요청을 여러개의 미들웨어가 처리할 수 있습니다.
// 요청 경로(path)가 포함되지 않은 요청은 항상 실행됩니다.
// function에서 next 인자를 처리하면 하위 스택을 처리하게 됩니다.
app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});


app.use(function(req, res){ // app.use에서 선언된 function이 미들웨어 입니다.
  res.send('Express Server!!!');
});

// client의 요청 경로(path)가 포함된 경우는 다음과 같이 처리합니다.
// app.use(path, 미들웨어함수);
app.use('/user/:id', function (req, res, next) {
  console.log('Request Type:', req.method);
  res.send('USER');
  next();
});

// next를 사용해서 미들웨어를 여러개 실행할 수도 있습니다.
app.use('/user/:id', function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

// 라우트 핸들러는 하나의 경로에 여러개의 라우트를 정의할 수 있습니다. 하지만 동일한 메소드를 2개 이상 만들고 앞에서 response를 처리하면 다음 메소드는 실행되지 않습니다.
app.get('/user/:id', function (req, res, next) {
  console.log('ID:', req.params.id);
  next();
}, function (req, res, next) {
  res.send('User Info');
});

// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
  res.end(req.params.id);
});

// ** 위 선언으로 라우터레벨 미들웨어를 다음과 같이 사용할 수 있습니다. 라우터에서도 use와 method를 사용합니다.
// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next router
  if (req.params.id == 0) next('route');
  // otherwise pass control to the next middleware function in this stack
  else next(); //
}, function (req, res, next) {
  // render a regular page
  res.render('regular');
});

// handler for the /user/:id path, which renders a special page
router.get('/user/:id', function (req, res, next) {
  console.log(req.params.id);
  res.render('special');
});

// mount the router on the app
app.use('/', router);

// 오류 처리 미들웨어는 function의 parameter 첫번째 인자로 error를 받아 처리합니다.
app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

// 기본 제공 미들웨어
// express에서 기본적으로 제공하는 미들웨어가 있습니다.
// 다음은 기본제공 미들웨어 중 정적 모듈을 처리하는 static 미들웨어의 예제입니다.
app.use(express.static(__dirname+'/public'))

// static으로 html 처리
// http://localhost:3000/index.html 로 요청이 올경우 /public/index.html을 찾아 응답하게 됩니다.
// static으로 이미지 처리
// http://localhost:3000/logo.png 로 요청이 올경우 /public/logo.png를 찾아 응답하게 됩니다.
// index.html 처리하기
// http://localhost:3000 을 응답하는 코드는 다음과 같습니다.
app.get('/', function(req, res) {
  res.sendFile(__dirname+'/public/index.html')
});

[유튜브강의] Smart Lab. 코드기어 NodeJS기초-11.Express 라우팅 분리하기 - 2025-02-15 (로봇)
[유튜브강의] Smart Lab. 코드기어 NodeJS기초-09.Express 서버 만들기1-특징과설치 - 2025-02-14 (로봇)
[유튜브강의] Smart Lab. 코드기어 NodeJS기초- 08.Http 서버만들기-1 - 2025-02-14 (로봇)


댓글목록

등록된 댓글이 없습니다.

Total 213건 1 페이지

검색

회원로그인

회원가입
새글

To Do List
  • Test 계정 만들기
  • 다른 회원의 스크랩 보기


사이트 정보

회사명 : 회사명 / 대표 : 대표자명
주소 : OO도 OO시 OO구 OO동 123-45
사업자 등록번호 : 123-45-67890
전화 : 02-123-4567 팩스 : 02-123-4568
통신판매업신고번호 : 제 OO구 - 123호
개인정보관리책임자 : 정보책임자명

접속자집계

오늘
151
어제
402
최대
970
전체
12,577
Copyright © 소유하신 도메인. All rights reserved.