본문 바로가기

Node.js

21. 라우팅(routing)

라우팅(routing)

- 웹 애플리케이션에서 클라이언트의 요청에 대해 적절한 핸들러 함수를 연결하는 과정

- 웹 애플리케이션은 다양한 URL 주소로 들어오는 요청을 처리해야 하는데, 이를 라우팅을 통해 각 요청에 대한 적절한 처리 로직을 연결하여 처리할 수 있음

 

express route 사용
import express from "express";

const app = express();

app.route(path);

 

express route 쿼리스트링 사용 예제

 

import express from "express";

const app = express();

app
    .route("/posts") // 경로 등록, 쿼리스트링으로 요청
    // get 방식 요청
    .get((req, res) =>{
        res.status(200).send("GET: /posts");
    })
    // post 방식 요청
    .post((req, res) =>{
        res.status(201).send("POST: /posts");
    });
    
app.listen(8080);

 

GET 방식으로 전송

http://localhost:8080/posts?number=1

 

POST 방식으로 전송

http://localhost:8080/posts?number=1

 

express route 라우팅 파라미터 사용 예제

 

import express from "express";

const app = express();

app
.route("/posts/:id") // 경로 등록, 라우팅 파라미터로 값 전달
// put 방식 요청
    .put((req, res) =>{
        res.status(201).send("PUT: /posts/:id");
    })
    // delete 방식 요청
    .delete((req, res) =>{
        res.status(200).send("DELETE: /posts/:id");
    });
    
app.listen(8080);

 

PUT 방식으로 전송

 

http://localhost:8080/posts/1

 

DLETE 방식으로 전송

http://localhost:8080/posts/1

 

Router 모듈 사용 예제

 

post.js

import express from "express";

const router = express.Router();

// 미들웨어 등록
router.use((req, res, next) => {
    console.log("posts에 존재하는 미들웨어!");
    next(); // next()를 사용하여 다음 미들웨어로 제어를 넘김
});

router.get('/',(req, res) =>{
    res.status(200).send("GET: /posts");
});
    
router.post('/',(req, res) =>{
    res.status(201).send("POST: /posts");
});

router.put("/:id",(req, res) =>{
    res.status(201).send("PUT: /posts/:id");
});

router.delete("/:id",(req, res) =>{
    res.status(200).send("DELETE: /posts/:id");
});

// 모듈을 내보냄
export default router;

 

router.js

import express from "express";
// 생성한 모듈을 import 해서 가져옴
import postRouter from "./routes/post.js";

const app = express();

app.use(express.json());
app.use("/posts", postRouter); // /posts 경로에 대한 미들웨어를 import한 postRouter로 등록

app.listen(8080);

 

GET 방식으로 전송

http://localhost:8080/posts?number=1

 

POST 방식으로 전송

http://localhost:8080/posts?number=1

 

PUT 방식으로 전송

http://localhost:8080/posts/1

 

DELETE 방식으로 전송

http://localhost:8080/posts/1

'Node.js' 카테고리의 다른 글

23. cors(Cross-Origin Resource Sharing)  (0) 2023.04.23
22. express.static  (0) 2023.04.23
20. error handling  (0) 2023.04.22
19. GET, DELETE, POST method  (0) 2023.04.22
18. express  (0) 2023.04.22