0Pricing
Node.js Backend Development Bootcamp · 강의

Express의 라우팅과 미들웨어

Express 라우팅을 익혀 API 엔드포인트를 정의하고 요청 처리를 위한 미들웨어를 구현합니다.

Express의 라우팅과 미들웨어은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Routing Your Express API

Welcome back! In this lesson, we'll dive into routing and middleware in Express. These are core concepts for building powerful and organized web applications.

Routing helps your server understand what to do when it receives different requests, like showing a user profile or saving new data.

Defining Basic Routes

A route tells your Express app how to respond to a specific type of request to a particular URL path. You define routes using methods like app.get(), app.post(), app.put(), and app.delete().

Each route method takes a path and a handler function that executes when the route is matched.

First GET Route Example

Let's create a simple GET route that responds to requests at the root URL (/). This is often your homepage or a basic API status check.

The handler function receives req (request) and res (response) objects.

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello from our Express API!');
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Handling Dynamic Route Parameters

Often, you need to capture dynamic values from the URL, like a user's ID. This is done with route parameters, denoted by a colon (:) in the path.

You can access these parameters through the req.params object in your route handler.

const express = require('express');
const app = express();
const port = 3000;

app.get('/users/:userId', (req, res) => {
  const userId = req.params.userId;
  res.send(`You requested user ID: ${userId}`);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

What is Middleware?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

They can:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

The 'next()' Function

The key to middleware is the next() function. If a middleware function does not end the request-response cycle (e.g., by calling res.send()), it must call next() to pass control to the next middleware function or route handler.

If next() is not called, the request will be left hanging.

Application-level Middleware

You can apply middleware globally to all requests using app.use(). This is great for tasks like logging, parsing JSON bodies, or setting common headers.

Let's create a simple logger that runs for every incoming request.

const express = require('express');
const app = express();
const port = 3000;

// Application-level middleware
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next(); // Don't forget to call next()
});

app.get('/', (req, res) => {
  res.send('Check your server console for the log!');
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Route-level Middleware

Sometimes, you only want middleware to run for specific routes. You can apply route-level middleware by passing it as an argument before the route handler function.

You can even chain multiple middleware functions for a single route.

const express = require('express');
const app = express();
const port = 3000;

// A simple authentication middleware
const isAuthenticated = (req, res, next) => {
  if (req.headers.authorization === 'Bearer mysecrettoken') {
    next(); // User is authenticated, proceed
  } else {
    res.status(401).send('Unauthorized: Invalid token');
  }
};

// Apply isAuthenticated middleware only to this route
app.get('/dashboard', isAuthenticated, (req, res) => {
  res.send('Welcome to the protected dashboard!');
});

app.get('/', (req, res) => {
  res.send('Public content here.');
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Common Middleware Uses

Middleware is incredibly versatile. Here are some common use cases:

  • Authentication/Authorization: Checking user credentials or permissions.
  • Logging: Recording request details for debugging or monitoring.
  • Body Parsing: Extracting JSON or URL-encoded data from request bodies (e.g., express.json()).
  • Error Handling: Catching and responding to errors (special middleware type).
  • Input Validation: Ensuring request data meets specific criteria.

Middleware & Routing Check

Let's test your understanding of Express routing and middleware!

Recap: Routing & Middleware

Great job! You've learned how Express uses routing to direct requests to specific handlers based on URL paths and HTTP methods.

You also mastered middleware, powerful functions that can intercept and process requests at various stages, either globally with app.use() or for specific routes. Understanding these concepts is fundamental to building robust Express applications!

자주 묻는 질문

“Express의 라우팅과 미들웨어” 강의는 무료인가요?

네 — “Express의 라우팅과 미들웨어” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“Express의 라우팅과 미들웨어”에서 뭘 배우나요?

Express 라우팅을 익혀 API 엔드포인트를 정의하고 요청 처리를 위한 미들웨어를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“Express의 라우팅과 미들웨어” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Express.js 프레임워크 기초
  2. Express의 라우팅과 미들웨어
  3. RESTful API 엔드포인트 설계
  4. 요청 데이터 처리: 본문, 쿼리 및 매개변수
← Node.js Backend Development Bootcamp(으)로 돌아가기