Node.js와 Express에서 클라이언트 요청 데이터를 주로 세 가지 방식으로 데이터를 받음
GET /products?category=electronics&sort=price&order=desc
app.get('/products', (req, res) => {
const category = req.query.category; // 'electronics'
const sort = req.query.sort; // 'price'
const order = req.query.order; // 'desc'
// category, sort, order를 사용하여 데이터 조회 로직 수행
res.send(`Category: ${category}, Sort by: ${sort}, Order: ${order}`);
});
GET /products/12345
GET /users/67890/orders
예시 1
// 동적 라우팅 설정
app.get('/products/:productId', (req, res) => {
const productId = req.params.productId; // '12345'
// productId를 사용하여 특정 상품 데이터 조회 로직 수행
res.send(`Product ID: ${productId}`);
});
예시 2
app.get('/users/:userId/orders', (req, res) => {
const userId = req.params.userId; // '67890'
// userId를 사용하여 해당 사용자의 주문 목록 조회
res.send(`User ID: ${userId}`);
});
POST /products
Content-Type: application/json
{
"title": "New Product",
"description": "Product description",
"price": 100
}
app.post('/products', (req, res) => {
const title = req.body.title; // 'New Product'
const description = req.body.description; // 'Product description'
const price = req.body.price; // 100
// title, description, price를 사용하여 새로운 상품 생성 로직 수행
res.send(`Product created: ${title}, ${description}, $${price}`);
});
| 방식 | 데이터 전달 | 예시 요청 | 접근 예시 |
|---|---|---|---|
req.query | URL 쿼리 스트링 | /products?category=electronics | req.query.category |
req.params | URL 경로의 동적 값 | /products/12345 | req.params.productId |
req.body | POST, PUT 등의 요청 본문 | {"name":"Product","price": 100} | req.body.title |