상세 컨텐츠

본문 제목

[CS] Query String / Path Variable

CS 과제 정리

by thisnorm 2025. 1. 13. 18:15

본문

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}`);
});
 

설명

  • URL: /users?occupation=programmer로 요청하면 "programmer" 직업을 가진 사용자를 요청하는 것입니다.
  • req.query를 사용하여 URL에서 전달된 쿼리 파라미터 값을 읽습니다.

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}`);
});

 
 

설명

  • URL: /users/123로 요청하면 123번 사용자 정보를 요청하는 것입니다.
  • req.params를 사용하여 URL 경로에서 전달된 Path Variable 값을 읽습니다.

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}`);
});

 

설명

  • URL: /users/123?occupation=programmer로 요청하면 123번 사용자의 정보와 "programmer" 직업을 가진 사용자를 요청하는 것입니다.
  • Path Variable은 req.params.id로, Query Parameter는 req.query.occupation으로 가져옵니다.

4. 전체 예시 실행하기

  1. 앱 실행: node app.js 명령으로 서버를 실행합니다.
  2. 테스트:
  • Query Parameter: http://localhost:3000/users?occupation=programmer
  • Path Variable: http://localhost:3000/users/123
  • Path Variable + Query Parameter: http://localhost:3000/users/123?occupation=developer

5. 정리

  • Path Variable:
  • 데이터의 고유 식별자나 특정 자원을 지정할 때 사용.
  • 예: /users/123 → ID가 123인 사용자 요청.
  • Query Parameter:
  • 데이터를 필터링하거나 정렬할 때 사용.
  • 예: /users?occupation=developer → 직업이 "developer"인 사용자 요청.

Express.js를 사용하면 req.paramsreq.query를 통해 Path Variable과 Query Parameter를 손쉽게 처리할 수 있습니다.

관련글 더보기