[Node] Express로 서버 구축

강준우·2023년 5월 12일
0

Node

목록 보기
1/1

npm init


익명의 폴더를 만들고 VS Code에서 터미널을 열고 npm init명령어를 입력한다.

C:\Project-Environment\server>npm init

이후 터미널에 나오는 명령어들이 나오는데, 일단은 엔터를 치며 모두 입력하면 다음과 같은 화면이 나오며 package.json 파일이 생성된 것을 알 수 있다.

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (server)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to C:\Project-Environment\server\package.json:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"    
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) yes
npm notice 
npm notice New major version of npm available! 7.18.1 -> 9.6.6
npm notice Changelog: https://github.com/npm/cli/releases/tag/v9.6.6
npm notice Run npm install -g npm@9.6.6 to update!
npm notice

package.json 파일을 보면 우리가 터미널에서 작성한(엔터친) 내용이 들어가 있음을 알 수 있다.

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

npm, package.json

Express


Node.js의 핵심 모듈인 http와 Connect 컴포넌트를 기반으로 하는 웹 프레임워크

Express는 쉽게 말해 Node.js를 사용하여 쉽게 서버를 구성할 수 있게 해주는 프레임워크이다. 우리는 Express를 사용해 서버를 구현할 것이다.

먼저 express를 설치를 해주어야 한다.

C:\Project-Environment\server>npm install express 

이전에는 package.json에 있는 dependencies에 설치하는 패키지를 추가하기 위해 --save 명령어를 설치시 적어주어야 했지만 npm@5 이후로는 --save 명령어 없이도 dependencies에 추가가 된다.

package.json파일을 다시 보면 다음곽 같이 dependenciesexpress가 최근 버전에 맞추어 적힌 것을 알 수 있다.

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

이외에도 node_modules 폴더와 package-lock.json 파일이 생성된다.

Express, Hello World


이제 express를 활용해 기초적인 서버를 만들어 보겠다.

Express 공식 문서에는 기초적인 서버 구축 예제를 제공하고 있다.

Express "Hello World" 예제

공식 문서에 적힌대로 app.js 파일을 생성 후, 다음의 소스코드를 붙여 넣어준다.

const express = require('express')
const app = express()
const port = 5000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

파일 저장 후, 터미널에 node app.js 명령어를 입력해준다.

C:\Project-Environment\server>node app.js
Example app listening on port 5000

다음과 같이 console에 메세지가 뜨는것이 확인 되었다면 주소창에 localhost:5000(본인 포트 번호)를 치면 화면에 Hello World!가 잘 출력된다.

npm run start


package.json을 보면 scripts 프로퍼티가 있다. scripts를 다음과 같이 작성하면 node app.js라 명령어를 입력하는 대신 npm start라는 명령어로 서버를 실행할 수 있다.

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node app.js", // <------추가
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

profile
강준우

0개의 댓글