본문 바로가기

JavaScript/Express.js

[Express.js] 프로젝트 세팅 (2)

Express 프로젝트 시작하기

  • package.json 설정
    - script : npm 명령어를 설정해 놓는 부분
    - main : 서버의 역할을 할 메인파일 명을 설정해 놓는 부분
{
  "name": "one-node-study",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "nodemon app"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^3.0.3"
  }
}

 

  •  app.js 설정
     - package.json의 main 부분에 해당하는 파일명으로 파일을 생성한다.
// ** 모듈 가져오기
const express = require("express");

// ** express 모듈을 변수에 할당
const app = express();

// ** Server Port 설정 (3000번)
app.set("port", 3000);

// ** GET / 요청시 함수 실행
app.get("/", (req, res) => {
  // 'Hello World!'를 전송한다.
  res.send("Hello World!");
});

// ** 서버 구동 (위에 설정한 포트로 서버를 구동한다.)
app.listen(app.get("port"), () => {
  // 서버가 구동되면서 실행될 함수
  console.log(`Server On Port ${app.get("port")}`);
});

 

  • 서버 실행
    - package.json의 script 부분에 미리 정의한 명령어를 통해 nodemon 실행
$ npm start

> one-node-study@1.0.0 start
> nodemon app

[nodemon] 3.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node app.js`
Server On Port 3000

 

  • / 경로로 접속하여 정상 작동 확인
    - 현재의 경우 로컬환경에서 서버를 구동중이기 때문에 localhost:3000 혹은 127.0.0.1:3000 으로 접속
       (아래와 같이 화면에 Hello World! 가 출력된다면 프로젝트 세팅에 성공한 것이다.)

Hello World!


github: https://github.com/DongyangOne/one-node-study