Node.js TIL 03

Nabang Kim·2021년 8월 6일
0

Node.js

목록 보기
3/6
post-thumbnail

2021년 8월 5일에 작성된 문서 3번 입니다.
node.js의 배운 내용을 정리했습니다.


Node.js Express

라우팅

  • 라우팅 : 애플리케이션 엔드 포인트(URI)의 정의, URI가 클라이언트 요청에 응답하는 방식
var express = require('express');
var app = express();

//홈페이지에 get요청이 도착을 하면,
app.get('/', function(req, res) {
  res.send('hello world');
  // "hello world"라고 답을 줌.
}); //라우팅 기본 방식



라우팅 메소드

  • express 클래스의 인스턴스에 연결
  • HTTP 메소드 중 하나로부터 파생 (get, post 등등)
  • var app = express(); : express 클래스 인스턴스는 app이니까 여기에 연결.
// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage');
});

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage');
});

특수 라우팅 메소드 : app.all()

  • 어떠한 HTTP 메소드로부터도 파생되지 않는다.
  • 모든 요청 메소드에 대해 한 경로에서 미들웨어 함수를 로드하는 데 사용.
app.all('/secret', function (req, res, next) {

// GET, POST, PUT 또는 DELETE 메소드를 사용하는 경우
// 또는 http 모듈에서 지원되는 기타 모든 HTTP 요청 메소드를 사용하는 경우
// secret에 대한 요청을 위하여 핸들러가 실행

  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler
});



라우트 경로

  • 요청 메소드와의 조합으로, 요청이 이루어질 수 있는 엔드포인트를 정의.
  • 라우트 경로는 문자열, 문자열 패턴 또는 정규식일 수 있다.
app.get('/', function (req, res) {
//라우트 경로는 요청을 루트 라우트 `/`에 일치
  res.send('root');
});

app.get('/about', function (req, res) {
//라우트 경로는 요청을 `/about`에 일치
  res.send('about');
});



라우트 핸들러

미들웨어와 비슷하게 작동하는 여러 콜백 함수를 제공하여 요청을 처리할 수 있다.
이 콜백은 next('route')를 호출하여 나머지 라우트 콜백을 우회할 수도 있다.
이러한 메커니즘을 이용하면 라우트에 대한 사전 조건을 지정한 후, 현재의 라우트를 계속할 이유가 없는 경우에는 제어를 후속 라우트에 전달할 수 있다.

//라우트 핸들러는 함수나 함수 배열의 형태 또는 둘을 조합한 형태
//하나의 콜백 함수는 하나의 라우트를 처리할 수 있다.
app.get('/example/a', function (req, res) { 
//여기가 콜백 함수 부분 => 요청 처리
  res.send('Hello from A!');
});


//2개 이상의 콜백 함수는 하나의 라우트를 처리
//이 때는 반드시 next 오브젝트를 지정해야 한다.
app.get('/example/b', function (req, res, next) { //콜백 1번
  console.log('the response will be sent by the next function ...');
  next(); //next 오브젝트를 지정
}, function (req, res) { //콜백 2번
  res.send('Hello from B!');
});


//하나의 콜백 함수 배열은 하나의 라우트를 처리할 수 있다.
var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}
var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}
var cb2 = function (req, res) {
  res.send('Hello from C!');
}
app.get('/example/c', [cb0, cb1, cb2]);


//독립적인 함수와 함수 배열의 조합은 하나의 라우트를 처리할 수 있다.
var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}
var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}
app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from D!');
});



응답 메소드

다음 표에 표시된 응답 오브젝트에 대한 메소드(res)는 응답을 클라이언트로 전송하고 요청-응답 주기를 종료할 수 있습니다. 라우트 핸들러로부터 다음 메소드 중 어느 하나도 호출되지 않는 경우, 클라이언트 요청은 정지된 채로 방치됩니다.

메소드형식설명
res.download()res.download(경로,[파일명],[옵션들],[fn])파일이 다운로드되도록 프롬프트
res.end()res.end([data],[인코딩 형식])응답 프로세스를 종료
res.json()res.json([바디])JSON 응답을 전송
res.jsonp()res.jsonp([바디])JSONP 지원을 통해 JSON 응답을 전송
res.redirect()res.redirect([상태], 경로)요청의 경로를 재지정
res.render()res.render(보기 템플릿,[locals],[콜백])보기 템플리트를 렌더링
res.send()res.send([바디])다양한 유형의 응답을 전송
res.sendFile()res.sendFile(경로,[옵션들],[fn])파일을 옥텟 스트림의 형태로 전송
res.sendStatus()res.sendStatus(상태 코드)응답 상태 코드를 설정한 후 해당 코드를 문자열로 표현한 내용을 응답 본문으로서 전송



app.route()

  • 라우트 경로에 대하여 체인 가능한 라우트 핸들러를 작성할 수 있다.
  • 경로는 한 곳에 지정되어 있어, 모듈식 라우트를 작성하면 중복성과 오타가 감소.
//체인 라우트 핸들러의 예시 (체인 형식)
app.route('/book')
  .get(function(req, res) {
    res.send('Get a random book');
  })
  .post(function(req, res) {
    res.send('Add a book');
  })
  .put(function(req, res) {
    res.send('Update the book');
  });



express.Router

  • 모듈식 마운팅 가능한 핸들러를 작성할 수 있다.
  • Router 인스턴스는 완전한 미들웨어이자 라우팅 시스템
//라우터를 모듈로서 작성하고, 
//라우터 모듈에서 미들웨어 함수를 로드하고, 
//몇몇 라우트를 정의하고, 기본 앱의 한 경로에 라우터 모듈을 마운트

var express = require('express');
var router = express.Router();

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;



Written with StackEdit.

0개의 댓글