본문 바로가기
IT/PROGRAM

Express 설치 . Node.js + Express 웹서버 구축하기

by SidePower 2022. 10. 3.

 

 Node.js

웹브라우저에서만 쓰이던 자바스크립트를 가져와서 서버 사이드 개발을 위한 런타임 환경

 Express

node.js를 이용하여 웹 및 모바일 애플리케이션을 위한

일련의 강력한 기능을 제공하는 간결하고 유연한 웹 애플리케이션 프레임워크

 

둘다 몇줄 안되는 코딩으로 웹서버를 만들수 있어 

저같은 웹 초보자들도 쉽게 시작할수 있을거 같아요.

 

 node.js 웹서버 샘플

 Hello World를 보여주는 간단한 웹서버

파일명 : node_one.js

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

 js 실행하기
C:\dev\nodejs>node node_one.js
Server running at http://127.0.0.1:3000/

브라우저에서 http://127.0.0.1:3000를 치면 Hello World가 나타난다.

 

 

 Express 설치

 

이미 node.js가 설치되어 있으므로 바로 express 설치할게요.

 프로젝트 폴더 만들기
C:\dev>mkdir hitapp

C:\dev>cd hitapp

 package.json 만들기
package.json 파일은 프로젝트 정의와 의존성 명시하는 파일입니다.

C:\dev\hitapp>npm init
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: (hitapp)   ▶여기에서 멈춰 있습니다. Enter키 계속 눌러 주세요.
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to C:\dev\hitapp\package.json:

{
  "name": "hitapp",
  "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  여기에서 yes 입력하고 Enter키 누르면 끝입니다.

C:\dev\hitapp>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\dev\hitapp 디렉터리

2021-12-22  오후 11:04    <DIR>          .
2021-12-22  오후 11:04    <DIR>          ..
2021-12-22  오후 11:04               202 package.json
               1개 파일                 202 바이트
               2개 디렉터리  72,827,244,544 바이트 남음

 package.json 파일 내용
{
  "name": "hitapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

 

 express 설치 명령어

npm install express [--save]

--save 옵션이 있으면 express가 설치되고 종속되는 모듈들도 자동으로 추가되어 설치합니다.

--save 옵션을 사용해주세요.

C:\dev\hitapp>npm install express --save

added 50 packages, and audited 51 packages in 7s

2 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

C:\dev\hitapp>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\dev\hitapp 디렉터리

2021-12-22  오후 11:22    <DIR>          .
2021-12-22  오후 11:22    <DIR>          ..
2021-12-22  오후 11:21    <DIR>          node_modules
2021-12-22  오후 11:21            31,917 package-lock.json
2021-12-22  오후 11:21               252 package.json
               3개 파일              32,409 바이트
               3개 디렉터리  72,825,966,592 바이트 남음

 

 express 웹서버 샘플

 node.js 샘플과 동일한 기능을 express로 만든 소스입니다.

파일명 : hit_1.js

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

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

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})


C:\dev\hitapp>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: A8FA-0147

 C:\dev\hitapp 디렉터리

2021-12-22  오후 11:27    <DIR>          .
2021-12-22  오후 11:27    <DIR>          ..
2021-12-22  오후 11:26               249    hit_1.js
2021-12-22  오후 11:21    <DIR>          node_modules
2021-12-22  오후 11:33            31,946 package-lock.json
2021-12-22  오후 11:33               252 package.json
               3개 파일              32,447 바이트
               3개 디렉터리  72,815,972,352 바이트 남음

 js 실행하기
C:\dev\hitapp>node hit_1.js
Example app listening at http://localhost:3000

 

 package.json 이용한 샘플 실행

scripts 항목에 명령어와 실행방법을 기록할 수 있습니다.

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


 scripts에 go 명령어 추가
  "scripts": {
    "go": "node hit_1.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }


 go 명령어로 실행
C:\dev\hitapp>npm run go

> hitapp@1.0.0 go
> node hit_1.js

Example app listening at http://localhost:3000

 

 

감사합니다.

반응형

댓글