본문 바로가기

Back-End/Node.js

Express - 5.1. 상세페이지구현 1 - Route Parameter

반응형

목표

홈페이지를 Express을 이용해 semantic url 방식으로 작성하기

-> url에 query string이 아닌 path방식을 통해 parameter가 전달되는 경우 처리하는 방법 알기

 


우리는 query string을 통해 우리가 가져오고 싶은 데이터를 웹 애플리케이션에게 전달한다. 즉, id값 전달을 통해 data 디렉토리에 있는 해당 파일을 읽어오는 것이다.

하지만 최근 query string이 포함된 주소를 아름답게 보지 않는 경향이 있다. 따라서 웹 트렌드 중 하나가 semantic url이다. 

(ex) localhost:3000/page/HTML

필요한 것

1. pathname = '/page' 지정

2. 콜백함수 실행될 때 '/HTML'를 가져오기

 

Express 페이지에서 가이드를 통해 라우팅에 관해 알아보자.

 

Express 라우팅

라우팅 라우팅은 애플리케이션 엔드 포인트(URI)의 정의, 그리고 URI가 클라이언트 요청에 응답하는 방식을 말합니다. 라우팅에 대한 소개는 기본 라우팅을 참조하십시오. 다음 코드는 매우 기본�

expressjs.com

 

라우트 파라미터

Route path: /users/:userId/books/:bookId

Request URL: http://localhost:3000/users/34/books/8989

req.params: { "userId": "34", "bookId": "8989" }

 

사용자가 직접 들어가는 주소(=Request URL)

- req객체에 params안에 객체가 들어가 있다.

- userId property값을 통해 34값을 가져올 수 있다.

 

구현

기본 형식

app.get('/users/:userId/books/:bookId', function (req, res) {
    res.send(req.params)
})

 

이전 코드

    if(pathname === '/'){
      // 1. home 페이지
      if(queryData.id === undefined){
        fs.readdir('./data', function(err, filelist){
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          var list = template.list(filelist);
          var html = template.html(title, list,
            `<a href="/create">create</a>`,
            `<h2>${title}</h2>${description}`);
          response.writeHead(200);  //200: 파일을 성공적으로 전송하였음
          response.end(html);
        });

Express 코드 및 결과

홈페이지

app.get('/', function(request, response){
  fs.readdir('./data', function(err, filelist){
    var title = 'Welcome';
    var description = 'Hello, Node.js';
    var list = template.list(filelist);
    var html = template.html(title, list,
      `<a href="/create">create</a>`,
      `<h2>${title}</h2>${description}`
    );
    response.send(html);
  });
});

그 외 링크 페이지

app.get('/page/:pageId', function(request, response){
  response.send(request.params);
});

결과

request.params값이 출력된다.

 

만약 아래와 같이 /:chapterId가 붙게 되면

app.get('/page/:pageId/:chapterId', function(request, response){
  response.send(request.params);
});

request.params 객체가 다음과 같이 된다.

반응형

'Back-End > Node.js' 카테고리의 다른 글

Node.js - get & post  (0) 2020.09.06
Express - 5.2. 상세페이지 구현 2  (0) 2020.09.06
Express - 4. 홈페이지 구현  (0) 2020.09.04
Express - 3.2. Hello Word 2  (0) 2020.09.04
Express - 3.1. Hello Word 1  (0) 2020.09.04