1. Query Parameter 예시
Query Parameter는 URL에서 ?key=value 형식으로 데이터를 전달하는 방식입니다. 주로 필터링, 정렬, 검색 등에 사용됩니다.
코드 예시 (Node.js와 Express.js)
const express = require('express');
const app = express();
const port = 3000;
// Query Parameter를 처리하는 엔드포인트
app.get('/users', (req, res) => {
// Query Parameter에서 'occupation'을 가져옵니다.
const occupation = req.query.occupation;
if (occupation) {
// 예: occupation=programmer일 때 필터링된 사용자 목록 반환
res.send(`Fetching users with occupation: ${occupation}`);
} else {
// occupation이 없으면 모든 사용자 목록 반환
res.send('Fetching all users');
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
설명
2. Path Variable 예시
Path Variable은 URL 경로에 직접 변수 값을 포함하여 데이터를 요청하는 방식입니다. 주로 고유 식별자(ID)와 같은 값에 사용됩니다.
코드 예시 (Node.js와 Express.js)
const express = require('express');
const app = express();
const port = 3000;
// Path Variable을 처리하는 엔드포인트
app.get('/users/:id', (req, res) => {
const userId = req.params.id; // Path Variable에서 'id' 값을 가져옵니다.
res.send(`Fetching user with ID: ${userId}`);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
설명
3. Path Variable과 Query Parameter 결합 예시
Path Variable과 Query Parameter를 결합하여 사용하면 더욱 유연한 요청을 처리할 수 있습니다. 예를 들어, 특정 ID의 사용자를 요청하면서, 해당 사용자의 정보를 필터링하거나 정렬하는 추가적인 조건을 Query Parameter로 전달할 수 있습니다.
코드 예시 (Node.js와 Express.js)
const express = require('express');
const app = express();
const port = 3000;
// Path Variable과 Query Parameter를 결합한 엔드포인트
app.get('/users/:id', (req, res) => {
const userId = req.params.id; // Path Variable에서 'id' 값 가져오기
const occupation = req.query.occupation; // Query Parameter에서 'occupation' 값 가져오기
if (occupation) {
res.send(`Fetching user with ID: ${userId} and occupation: ${occupation}`);
} else {
res.send(`Fetching user with ID: ${userId}`);
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
설명
4. 전체 예시 실행하기
5. 정리
Express.js를 사용하면 req.params와 req.query를 통해 Path Variable과 Query Parameter를 손쉽게 처리할 수 있습니다.
[CS] DI, IoC, 그리고 ORM: 개발 생산성을 높이는 핵심 개념 완벽 정리 (3) | 2025.01.16 |
---|---|
[CS] RDBMS와 NoSQL의 차이점: 데이터베이스 선택의 모든 것 (2) | 2025.01.14 |
[CS] 서버 개발을 위한 기초 CS 지식 정리 (1) | 2025.01.10 |
[CS] 브라우저 검색 시 클라이언트-서버 흐름 (5) | 2025.01.09 |
[CS] 객체지향 프로그래밍 5가지 설계 원칙 (1) | 2025.01.09 |