2013년 6월 11일 화요일

express - app.render, res.render

0. express 공식 홈페이지
 - http://expressjs.com/

1. app.render(), res.render()
 - api reference를 봐도 이해하기가 쉽지 않네요.

2. http://stackoverflow.com/questions/15403791/in-express-js-app-render-vs-res-render-whats-the-difference
 - 그래서 위 사이트의 answers를 참고해 봅니다.


1. You can call app.render on root level and res.render only inside a route/middleware
 --> 밑에 코드 예시를 보면 res.render()의 경우 단독으로 사용되지 않고 app.get()의 콜백 함수 안에서 실행됩니다. 그래서 route/middleware라는 표현을 했습니다.

2. app.render always returns the html in the callback function 
--> html 을 리턴하는데 이건 클라이언트로 전송이 안됩니다. 즉 string이 리턴된다는 거죠. 아래 처럼 로그남기는 용도 등으로 사용할 수 있겠습니다.
whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third paramter/callback function the rendered html is sent to the client with a status code of 200. Take a look at the following examples
app.render
app.render('index', {title: 'res vs app render'}, function(err, html) {
  console.log(html)
});

// logs the following string (from default index.jade)
<!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
res.render without third parameter
app.get('/render', function(req, res) {
  res.render('index', {title: 'res vs app render'})
})

// also renders index.jade but sends it to the client 
// with status 200 and content-type text/html on GET /render
--> 위 코드는 클라이언트로 전송이 됩니다. res.render()를 까보면 res.send()가 들어가 있습니다.
res.render with third parameter
app.get('/render', function(req, res) {
  res.render('index', {title: 'res vs app render'}, function(err, html) {
    console.log(html);
    res.send('done');
  })
})

// logs the same as app.render and sends "done" to the client instead 
// of the content of index.jade

--> third param으로 callback function이 들어가 있네요 (function(err,html){}) 즉 이경우에는 app.render() 처럼 html string이 콜백 parameter로 들어갑니다. 그 후에 res.send()를 통해서 클라이언트로 'done'을 전송했네요.

댓글 없음:

댓글 쓰기