nodejs

[Express]

퓨처디벨로퍼 2021. 12. 2. 02:41

순수한 node.js 기능만 가지고 직접 웹 애플리케이션을 구현하는 것은 다소 불편하다. 

-> 웹프레임워크를 만들기 시작. 

 

웹프레임워크란?

반복적으로 어디에서나 등장하는 일들을 처리할 때 더 적은 코드와 지식으로도 더 많은 일을 보다 안전하게 처리할 수 있도록 도와주는 도구 

 

Express

: nodejs에서 가장 보편적으로 사용되는 프레임워크 중에 하나.

 

 

Routing(라우팅)

 

express 사용할 때 라우팅하는 법. 

//route,routing : 사용자들이 여러가지 패스를 통해서 들어올 때 패스마다 적당한 응답을 해주는 것.
// '/' 경로로 들어왔을 때 호출될 함수.
/*app.get('/', function(req, res){
    return res.send('Hello World!')
});*/

app.get('/', (req, res) => {
  res.send('/')
})

app.get('/page', (req, res) => {
  res.send('page')
})

//3000번 포트를 리스닝하게되고 성공하면 뒤에 코드 실행되게 약속.
app.listen(3000, function(){
  console.log(`Example app listening at http://localhost:${port}`)
});

 

express 프레임워크를 사용하지 않을 때, 라우팅 하는 방법. 

  if(pathname === '/'){
      if(queryData.id === undefined){
        fs.readdir('./data', function(error, filelist){
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          var list = template.list(filelist);
          var html = template.HTML(title, list,
            `<h2>${title}</h2>${description}`,
            `<a href="/create">create</a>`
          );
          response.writeHead(200);
          response.end(html);
        });
      } else {

 

Route Parameter

 

// page/34, 로 들어왔을때 34는 pageId.
app.get('/page/:pageId', (req, res) => {
  res.send(req.params) //pageId값은 req.params에 들어가있다. 
})