Node.js Express(고급)

Jelkov Ahn·2021년 10월 25일
0

HTTP / 네트워크

목록 보기
8/11
post-thumbnail

라우팅메소드

라우트 메소드는 HTTP 메소드 중 하나로부터 파생되며, express 클래스의 인스턴스에 연결됩니다.

ex) GET/POST

// 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');
});

Express는 HTTP 메소드에 해당하는 다음과 같은 라우팅 메소드를 지원합니다.
get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, propfind, proppatch, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch, search 및 connect.

  • 올바르지 않은 JavaScript 변수 이름으로 변환되는 메소드를 라우팅하려면 대괄호 표기법을 사용하십시오.
    ex) app['m-search']('/', function ... 등과 같습니다.

app.all()

  • 이 메소드는 모든 요청 메소드에 대해 한 경로에서 미들웨어 함수를 로드하는 데 사용됩니다.

  • http 모듈에서 지원되는 기타 모든 HTTP 요청 메소드를 사용하는 경우 등의 “/secret”에 대한 요청을 위하여 핸들러가 실행됩니다.

app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler
});

라우트 경로

라우트 경로는, 요청 메소드와의 조합을 통해, 요청이 이루어질 수 있는 엔드포인트를 정의합니다.
라우트 경로는 문자열, 문자열 패턴 또는 정규식일 수 있습니다.

문자열 기반

/

app.get('/', function (req, res) {
  res.send('root');
});

/about

app.get('/about', function (req, res) {
  res.send('about');
});

acd 및 abcd

app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});
//'/ab?cd' - > b가 맞거나 틀리거나 / abcd/ acd

abcd, abbcd 및 abbbcd

app.get('/ab+cd', function(req, res) {
  res.send('ab+cd');
});
// b+ b가 더해질수 있다.

abcd, abxcd, abRABDOMcd 및 ab123cd

app.get('/ab*cd', function(req, res) {
  res.send('ab*cd');
});
//*아무거나 들어올수 있다.

/abe 및 /abcde

app.get('/ab(cd)?e', function(req, res) {
 res.send('ab(cd)?e');
});
//() 안에 생략 가능

정규식 기반

라우트 이름에 “a”가 포함된 모든 항목

app.get('/ab(cd)?e', function(req, res) {
 res.send('ab(cd)?e');
});

butterfly 및 dragonfly와 일치하지만, butterflyman 및 dragonfly man 등과 일치하지 않습니다.

app.get(/.*fly$/, function(req, res) {
  res.send('/.*fly$/');
});

라우트 핸들러

미들웨어와 비슷하게 작동하는 여러 콜백 함수를 제공하여 요청을 처리할 수 있습니다. 유일한 차이점은 이러한 콜백은 next('route')를 호출하여 나머지 라우트 콜백을 우회할 수도 있다는 점입니다.

하나의 라우트

app.get('/example/a', function (req, res) {
  res.send('Hello from A!');
});

2개 이상의 콜백 함수는 하나의 라우트를 처리할 수 있습니다

app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from B!');
});
  • 하나의 콜백 함수 배열은 하나의 라우트를 처리할 수 있습니다.
  • 독립적인 함수와 함수 배열의 조합은 하나의 라우트를 처리할 수 있습니다.

응답 메소드

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

app.route()

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

express.Router 클래스를 사용하면 모듈식 마운팅 가능한 핸들러를 작성할 수 있습니다. Router 인스턴스는 완전한 미들웨어이자 라우팅 시스템이며, 따라서 “미니 앱(mini-app)”이라고 불리는 경우가 많습니다.

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;

이후 앱 내에서 다음과 같이 라우터 모듈을 로드하십시오.

var birds = require('./birds');
...
app.use('/birds', birds);

앱은 이제 /birds 및 /birds/about에 대한 요청을 처리할 수 있게 되었으며, 해당 라우트에 대한 특정한 미들웨어 함수인 timeLog를 호출할 것입니다.

미들웨어가 할수 있는 일

  1. Cors 헤더 자동 적용
  2. body를 text든 json이든 알아서 잘 해석해 줌.
  3. 에러처리와 디버깅에 용이 ( 모든 요청에 대해 Url이나 메소를 확인해줌)
  4. 권한에 따른 처리가능 ( 헤더에 있는 인증정보를 통해)
  5. Prefix(접두어)가 중복될때 라우팅을 편하게

미들웨어의 역할

미들웨어의 예시

const myLogger = (req, res, next) => {
  const { method, url} = req
  console.log(method,url)
  next() 다른 미들웨어를 실행시켜려면 next를 써야한다 마지막에!

인증정보 미들웨어 만들기 예시

const checkAdmin = (req, res, next) => {
  if(req.headers.Authentication === '관리자') {
    next()
  }
  else {
    res.send('관리자 아니니까 나가')
  }
}

app.post('/admin-only', checkAdmin, (req,res) =>{
  
  })

미들웨어 관련 내용 공부 :https://expressjs.com/ko/guide/writing-middleware.html

profile
끝까지 ... 가면 된다.

0개의 댓글