[Node.js] express초기 세팅

jaylight·2021년 3월 10일
0
  • 나중에 내가 보려고 쓰는 초기 세팅 루트
  1. 프로젝트 폴더 생성
  2. package.json 생성
> npm init
  1. package.json 초기 설정
{
  "name": "initial",
  "version": "0.0.1",
  "description": "초기 세팅 실습",
  "main": "app.js",
  "scripts": {
    "start": "nodemon app",
  },
  "author": "",
  "license": "MIT",
}
  1. express, nodemon 설치
> npm i express
> npm i -D nodemon

nodemon

  • 서버 코드 수정 시 서버를 자동으로 재시작해줌
  • package.json에서 scripts.start를 "nodemon app"으로 설정하면 app.js를 nodemon으로 실행
  • 개발용으로 사용하는 것을 권장
  1. app.js 생성 및 내용 수정
const express = require('express');

const app = express();

// 서버가 실행될 포트를 설정
app.set('port', process.env.PORT || 3000);

// 첫번째 인수로 주소를 넣지 않는다면, 모든 요청에서 실행되는 미들웨어
app.use((req, res, next) => {
    console.log('모든 요청에 다 실행됩니다.');
    next();
})

// 주소에 대한 GET 요청이 올 때 어떤 동작을 할지 정의
// req: 요청에 관한 정보가 들어 있는 객체
// res: 응답에 관한 정보가 들어있는 객체
app.get('/', (req, res, next) => {
    //res.send('Hello, Express')
    //res.sendFile(path.join(__dirname, '/index.html'));
    console.log('GET / 요청에서만 실행됩니다.');
    next();
}, (req, res) => {
    throw new Error('에러는 에러 처리 미들웨어로 갑니다.')
});

app.use((err, req, res, next) => {
    console.error(err);
    res.status(500).send(err.message);
})

// http 웹 서버와 동일
app.listen(app.get('port'), () => {
    console.log(app.get('port'), '번 포트에서 대기 중');
});

0개의 댓글