티스토리 뷰

express setup 하기

노마드코더 youtube 클론 강좌 기준으로 한 기본 세팅입니다.

완성 상태

1) app.js

import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import express from "express";
import helmet from "helmet";
import morgan from "morgan";

const app = express();

app.use(helmet());
app.set("view engine", "pug");
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan("dev"));
app.use(localsMiddlewares);

export default app;

2) init.js

import app from "./app";

const PORT = 4000;
const handleListening = () => console.log(`>>>> Listening on: http://localhost:${PORT}`);

app.listen(PORT, handleListening);

3) package.json

{
  "name": "wetube",
  "version": "1.0.0",
  "description": "youtube clone",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon --exec babel-node init.js --delay 2"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/simyeongryu/wetube.git"
  },
  "author": "simyeongryu",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/simyeongryu/wetube/issues"
  },
  "homepage": "https://github.com/simyeongryu/wetube#readme",
  "dependencies": {
    "@babel/core": "^7.8.4",
    "@babel/node": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "body-parser": "^1.19.0",
    "cookie-parser": "^1.4.4",
    "express": "^4.17.1",
    "helmet": "^3.21.2",
    "morgan": "^1.9.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.2"
  }
}

세팅 과정

1. 프로젝트 초기화

$ npm init

패키지 이름 등 기본적인 정보를 설정한다.

이 명령을 수행하면 프로젝트 폴더에 package.json 파일이 생성되는데, 해당 파일에 프로젝트를 위한 의존성들이 설정된다.

이 이후에 설치를 진행할 땐 반드시 이 pakage.json이 있는 폴더 내에서 수행한다. 그렇지 않으면 이곳저곳에 pakage.json이 생성되어 의존성이 잘 관리되지 않고, 프로젝트가 정상적으로 실행되지 않는다.

2. express 설치

$ npm install express

express를 설치하고 app.js라는 파일을 만들고 import한다.

참고: https://expressjs.com/

import express from "express";

const app = express();

babel을 사용하지 않는다면

const express = require("express");

const app = express();

babel 없이 import 를 사용하면 syntax error가 발생한다.

3. 각종 패키지 설치

helmet

$ npm install helmet
import helmet from "helmet";

app.use(helmet());

보안을 위한 필수 모듈이다. 웹의 헤더 설정을 변경하여 보안성을 올려준다.

미들웨어들을 설정할 때 가장 상단에 설정해서 모든 라우터에 적용될 수 있게 하자.

참고: http://expressjs.com/ko/advanced/best-practice-security.html

babel

$ npm install @babel/node

$ npm install @babel/core

$ npm install @babel/preset-env

브라우져 호환성을 위해 사용한다. 최신의 자바스크립트를 예전 자바스크립트로 바꿔 브라우져에 전달한다. 아직 최신의 자바스크립트를 이해하지 못하는 브라우져들을 위한 통역가로 생각하면된다.

바벨에는 여러가지 프리셋이 존재한다. 어느정도의 강도(?)로 번역할지 정하는 건데 일단 env 정도면 무난하다고 알고 있다. 아직 정확히 알지는 못한다. 더 공부하면 추가해놔야겠다.

설치 이후에 는 프로젝트 파일에 .babelrc라는 파일을 생성하여 아래의 내용을 작성한다.

{
    "presets": 
      [
        "@babel/preset-env"
      ]
}

위의 내용은 babel 공식 사이트에서도 찾을 수 있다.

참고: https://babeljs.io/

nodemon

$ npm install nodemon -D

소스코드를 수정하고 저장하면 자동으로 서버를 재시작해주는 모듈이다. 작업의 중간 과정을 확인하기 위해 서버를 수동으로 껐다 켰다 할 필요가 없어져서 굉장히 유용한 모듈.

설치 명령어에서 -D는 해당 모듈이 프로젝트 실행에 반드시 필요한 것이 아니라 개발자의 편의를 위한 모듈이니 package.jsondevDependencies에 저장하겠다는 뜻이다. 프로젝트 실행에 반드시 필요한 것들은 dependencies에 저장된다.

morgan

$ npm install morgan
import morgan from "morgan";

app.use(morgan("dev"));

로그 기록 모듈. morgan() 에 어떤 인자를 넣느냐에 따라 로그 기록의 정도가 정해진다. dev는 중간정도로 자세하다. 나머지 인자들은 아래 사이트 참조.

참고: https://github.com/expressjs/morgan

cookie-parser, body-parser

$ npm install cookie-parser
$ npm install body-parser
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

쿠키값을 얻게 해주는 모듈과 form에서 넘어오는 값을 얻게 해주는 모듈.

.gitignore

github에 push 할 때 업로드되지 않을 파일들을 설정.

기본적으로 github에서 제공하는 node.js 맞춤 gitignore 내용에

express를 설치하면 생기는 node_modules폴더와 package-lock.json를 추가로 제외한다.

node_modules는 용량이 너무 크고, push할 필요가 없다. package.json 파일만 있으면 npm install로 필요한 모든 모듈을 다운로드 받을 수 있다.

package-lock.json은 정보 보안을 위해 통상적으로 제외하지만 경우에 따라 제외하지 않는 경우도 있다고 한다. 하지만 난 아직 경험이 없어서 일단 넣어둔다.

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# node_modules 
node_modules

# package-lock.json
package-lock.json

package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon --exec babel-node init.js --delay 2"
  },

scripts라는 key를 추가하고 start라는 값을 추가한다.

이걸 설정하면 npm start 만으로 설정된 구문을 실행할 수 있다.

  • nodemon --exec : nodemon을 실행한다.
  • babel-node init.js : babel로 node.js를 실행하며 init.js라는 파일을 실행한다.
  • --delay 2 : nodemon을 2초 있다가 실행한다. 즉, 서버가 2초 후에 재시작된다. babel이 소스코드를 해석할 시간을 준 것.

pug

$ npm install pug
app.set("view engine", "pug");
// app.set("views", "./views");

view engine. html 코드를 마치 파이썬처럼 작성할 수 있게 해준다. 필수 모듈은 아니다.

app.set("views")는 기본값이 프로젝트 폴더 내 ./views 로 설정되어 있다. 그대로 사용할 거라면 설정하지 않아도 된다. 변경할 거라면 아래 사이트 참조.

app.set 참고: https://expressjs.com/en/4x/api.html#app.set

'Programming' 카테고리의 다른 글

npm Xcode 에러 해결하기  (0) 2020.12.20
npm ERR! code ELIFECYCLE 해결하기  (0) 2020.12.20
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함