[Nodejs] express 구조, 라우팅 방법, package-lock.json 사용이유
Express
node를 위한 빠르고 간결한 웹 프레임워크로 기존 메소드 + 편리한 메소드 추가해서 기능 보완했다.
(프레임워크란 ? 설계의 기반이 되는 부분을 기술한 확장 가능한 기반 코드 + 필요한 라이브러리 통합되어 제공하는 형태)
HTTP요청에 대해 라우팅 및 미들웨어 기능 제공
라우팅 : 서버경로제어, 통신 데이터를 보낼 경로 선택
미들웨어 : 부가적인 기능이나 처리를 제공하는 목적
express-generator
Nodejs + Express 구조의 뼈대를 만들 수 있다
설치 : npm install -g express-generator
프로젝트 생성 : express 생성할프로젝트이름
서버 시작 : npm start
모듈 설치 : npm install
프로젝트 구조
./package-lock.json 파일이란?
npm을 사용해 node_modules 트리 OR package.json파일을 수정하면 자동으로 생성되는파일
이 파일은 파일이 생성되는 시점의 의존성 트리에 대한 정확한 정보를 가지고 있다.
필요한 이유?
1. 의존성 트리에 대한 정보를 모두 가지고 있다.
2. github 저장소에 꼭 같이 커밋을 해야한다. 특히, node_modules 없이 배포하는 경우 반드시 필요하다!!
예시) node_modules 폴더를 제외하고 저장된 저장소의 파일을 pull 받았을 때
./package-lock.json 없으면 ? => 의존성 트리의 일부 버전이 다르게 설치됨
있으면 ? => 동일한 버전으로 잘 설치됨
/routes 파일 기본 구조
var express = require('express');
var router = express.Router();
router.get('/', function(req, response, next){
});
module.exports = router;
request처리
req.query : url query문자열
url?str=hello console.log(req.query.str) //결과 : hello
req.params : url에서 변수로 넘어온 것
url/idx url/1004 console.log(req.params.str) //결과 : 1004
req.body : body로 넘어온 값
req.file : 파일을 전송받았을 떄
response처리
res.status() : 정수 값으로 status code 작성
res. send() : JSON형식으로 response body작성
라우팅 - 파일 접근 방법
>config
dbconfig.js
>errors
DatabaseError.js
DuplicatedEntryError.js
index.js
NoReferenceRowError.js
NotMatchedError.js
ParameterError.js
>models
Comment.js
Todo.js
>modules
>db
pool.js
>utils
index.js
responseMessage.js
statusCode.js
util.js
>routes
>todos
>todos.js
>index.js
router.use('/:todoId/comments', require('./comments'));
router.use('/', require('./todos'));
>comments
>comments.js
>index.js
router.use('/', require('./comments'));
>index.js
router.use('/todos', require('./todos'));
>app.js
const indexRouter = require('./routes/index');
app.use('/', indexRouter);
>index.js
1. app.js : 라우팅의 시작점. require('./routes/index')를 통해 routes/index 폴더 호출.
2. routes/index
3. routes/todo/index
4. routes/todo/comments/index