Differences between express.Router and app.get?

I'm starting with NodeJS and Express 4, and I'm a bit confused. I been reading the Express website, but can't see when to use a route handler or when to use express.Router. As I could see, if I wa...

stackoverflow.com

 

 

app.js
var express = require('express'),
    dogs    = require('./routes/dogs'), // 모듈로 만든 라우터들을 사용
    cats    = require('./routes/cats'),
    birds   = require('./routes/birds');

var app = express();

app.use('/dogs',  dogs);
app.use('/cats',  cats);
app.use('/birds', birds);

app.listen(3000);

 

use메서드는 모든 HTTP 메서드에 대해 요청 주소만 일치하면 실행되지만

get, post, put, patch, delete 같은 메서드는 주소뿐만 아니라 HTTP 메서드까지 일치하는 요청일 때만 실행된다. 

- express()는 listen()을 이용해 수신한다.

 

 

 

routes/dog.js
var express = require('express');

var router = express.Router();

router.get('/', function(req, res) {
    res.send('GET handler for /dogs route.');
});

router.post('/', function(req, res) {
    res.send('POST handler for /dogs route.');
});

module.exports = router; // 라우터를 모듈화

 

router에도 app처럼 use, get, post, put, patch, delete 같은 메서드를 붙일 수 있다. use를 제외하고는 각각 HTTP 요청 메서드와 상응한다.

라우터에서는 반드시 요청에 대한 응답을 보내거나 에러 핸들러로 요청을 넘겨야 한다. 응답을 보내지 않으면 브라우저는 계속 응답을 기다린다. res객체에 들어 있는 메서드들로 응답을 보낸다.

- Router는 요청에 대해 listen()을 사용하지 않는다.

 

 

두 가지 경우 차이점

var app = express()가 호출되면 앱 객체가 반환된다. 이것을 Main app으로 생각한다.
var router = express.Router()가 호출되면 Main app과는 조금 다른 Mini app이 반환된다.

 

코드(미들웨어)가 복잡해지는 것을 방지하고 재사용성을 높이기 위해 각 라우터를 별도의 모듈로 만드는 것이다. 즉, 각 기능에 맞는 Mini app을 만들고 그것들을 Main app에서 불러와 사용하는 것이다.

 

위의 예에서, /dogs 경로에 대한 코드는 메인 앱을 복잡하게 하지 않도록 자체 파일로 이동했다. /cats와 /birds에 대한 코드는 그들 자신의 파일에서 유사한 구조가 될 것이다. 이 코드를 세 개의 미니 앱으로 분리하면 각각을 위한 logic 작업을 따로 할 수 있고, 나머지 두 개에 어떤 영향을 미칠지 걱정하지 않아도 된다.

 

반응형

'Node.js > Express' 카테고리의 다른 글

[Express] Body-Parser 미들웨어 다루기  (0) 2020.12.04
 

mongoose

Mongoose MongoDB ODM

www.npmjs.com

 

1. Mongoose ?

Node.js 비동기 환경에서 동작하도록 디자인 된 몽고DB 모델링 툴이다. Mongoose는 promise와 callback 모두 지원한다.

 

2. 설치

$ npm install mongoose --save

 

3. 불러오기(importing)

// Using Node.js `require()`
const mongoose = require('mongoose');
 
// Using ES6 imports
import mongoose from 'mongoose';

 

4. 몽고DB 연결

만약 하나의 DB만 사용한다면, mongoose.connect()를 사용하고, 만약 추가적인 연결들이 필요할 경우에 mongoose.createConnection()을 사용한다. 두 가지 경우 모두 mongodb://URI 또는 host, database, port, options 같은 파라미터를 받습니다.

 

// npm공식 문서 사용 예시
mongoose.connect('mongodb://localhost/my_database', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
  useCreateIndex: true
});

 

// 사용 예시
// config.mongoURI --> 몽고DB url을 외부 모듈(config라는 명)로 만들어 불러서 사용한 경우
mongoose.connect(config.mongoURI, {
  useNewUrlParser: true, 
  useUnifiedTopology: true, 
  useCreateIndex: true, 
  useFindAndModify: false
})
.then(() => console.log('MongoDB Conneted...'))
.catch(err => console.log(err));

 

여기서 몽고 DB 가 Local 일 경우 주소만 해당되지만 클라우드를 통해서 올 때는 비밀번호까지 들어가기 때문에 조심해야 한다.

 

 

5. 스키마 정의 & 모델화

 

var mySchema = mongoose.Schema({
    name : 'string',
    address : 'string',
    age : 'number'
});
// mongoose.model('ModelName', mySchema)
const MyModel = mongoose.model('ModelName');

정의된 스키마를 객체처럼 사용할 수 있도록 model() 함수로 컴파일한다.

 

 

6. 모델 객체 생성 후 데이터 입력

const newInfo = new MyModel({name:'Hong Gil Dong', address:'서울시 강남구', age:'26'});

new를 이용해 모델 객체를 생성해 데이터를 입력해준다.

 

7. 데이터 저장

newInfo.save(function(error, data){
    if(error){
        console.log(error);
    }else{
        console.log('Saved!')
    }
});
  • Model.save(function(err,product)); : Callback

  • Model.save().then(resolved,rejected); : Promise

 

8. 데이터 가져오기

// find(): 전체 데이터 불러오기, findOne() : 데이터 하나 가져오기
MyModel.find({}, function (err, docs) {
  // docs.forEach
});

// 예제
newInfo.find(function(error, students){
    console.log('--- Read all ---');
    if(error){
        console.log(error);
    }else{
        console.log(students);
    }
})

 

 

9. 데이터 수정하기

// 특정 id에 해당하는 데이터 수정
MyModel.findOne({_id:'585b777f7e2315063457e4ac'}, function(error,student){
    if(error){
        console.log(error);
    }else{
        student.name = '김철수';
        student.save(function(error,modified_student){
            if(error){
                console.log(error);
            }else{
                console.log(modified_student);
            }
        });
    }
});

// update() 이용방법도 있다.

 

 

10. 데이터 삭제하기

MyModel.findOne({title:'아바타'}, function(err, doc) {
   if ( doc ) {
      doc.name = '홍길동';
      doc.remove(function(err, product) {
         console.log('Find and Remove : ', err, product);
      });         
   }
});

// remove()함수 이용 
MyModel.remove({job:'학생'}).then(resolved, rejected);
반응형

 

모든 npm 패키지에는 보통 프로젝트 루트에 package.json이라는 파일이 들어 있다. 이 파일에는 프로젝트와 관련된 다양한 메타데이터가 저장되어 있다. 이 파일은 프로젝트의 종속성(dependencies)을 처리할 뿐만 아니라 프로젝트를 식별할 수 있는 정보를 npm에 제공하는 데 사용된다. 또한 프로젝트 설명, 특정 배포의 프로젝트 버전, 라이선스 정보, 구성 데이터 등과 같은 다른 메타데이터도 포함할 수 있으며, 이 모든 메타데이터는 npm과 패키지의 최종 사용자에게 필수적일 수 있다. package.json 파일은 일반적으로 Node.js 프로젝트의 루트 디렉터리에 위치한다.

 

 

Node.js 자체는 패키지의 다음의 두 필드만 인식한다.

{
  "name" : "프로젝트 이름",
  "version" : "0.0.0",
}

 

- name : 해당 프로젝트의 이름을 작성해주면 된다.

- version : 올바른 버전의 패키지가 설치되고 있는지 확인하기 위해 npm에서 사용한다.

일반적으로 major.minor.patch의 형태를 취하는데, major, minor, patch는 major, minor, patch는 매 신규 출시 후 증가하는 정수다.

 

 

 

{
  "name" : "underscore",
  "description" : "JavaScript's functional programming helper library.",
  "homepage" : "http://documentcloud.github.com/underscore/",
  "keywords" : ["util", "functional", "server", "client", "browser"],
  "author" : "Jeremy Ashkenas <jeremy@documentcloud.org>",
  "contributors" : [],
  "dependencies" : [],
  "repository" : {"type": "git", "url": "git://github.com/documentcloud/underscore.git"},
  "main" : "underscore.js",
  "version" : "1.1.6"
}

 

 

보시다시피 프로젝트의 설명(description) 및 키워드(keywords) 필드가 있다. 이것은 당신의 프로젝트를 찾은 사람들이 그것이 무엇인지 단 몇 마디 말로 이해할 수 있게 해준다. 작성자(author), 기고자(contributors), 홈페이지(homepage), 리포지토리(repository) 분야는 모두 프로젝트에 기여한 사람들을 신용하고, 작성자/유지인에게 연락하는 방법을 보여주며, 추가 참조를 위한 링크를 제공하는 데 사용할 수 있다.

 

main 필드에 나열된 파일은 라이브러리의 주요 진입점이며, 누군가 require(<library name>) 으로 실행하려면 require(<package.json:main>) 식으로 호출해 라이브러리를 사용할 수 있다. dependencies 필드는 npm에서 사용할 수 있는 프로젝트의 모든 dependencies을 나열하는 데 사용된다. 누군가가 npm을 통해 당신의 프로젝트를 설치하면, 나열된 모든 dependencies 또한 설치될 것이다. 또한 다른 사용자가 프로젝트의 루트 디렉토리에서 npm 설치를 실행하면 ./node_modules에 모든 dependencies을 설치하게 된다.

 

devDependencies 필드를 package.json에 추가할 수도 있다. 이러한 종속성은 정상 작동에 필요한 것이 아니라 프로젝트를 패치하거나 수정하려는 경우 필수/권고 사항이다. 예를 들어, 테스트 프레임워크를 사용하여 장치 테스트를 작성한 경우 devDependency 필드에 사용한 테스트 프레임워크를 넣는 것이 적절할 것이다. 프로젝트의 devDependencies를 설치하려면 npm 설치를 사용할 때 --dev 옵션을 넣으면된다.

반응형

+ Recent posts