개발/웹서버 만들기

Express를 사용하여 간단한 웹 서버 구축

B.바보 2025. 5. 18. 02:02

Express 실행 예제

const express = require('express');
const app = express();

app.listen(8080, function(){
    console.log('Server is running on port 8080');
});

app.get('/', function(req, res){
    res.send('Hello World');
});

app.get('/hello', function(req, res){
    res.send('Hello?');
});
  • 위의 코드를 server.js에 입력하여 저장함.
node server.js
  • 콘솔(Terminal)창에 위의 명령어를 입력함.

Express 라이브러리 불러오기

const express = require('express');
const app = express();
  • require('express') : Express 모듈을 사용함.
  • const app = express(); : Express 애플리케이션 객체를 생성하며, 해당 객체는 라우팅과 서버 설정 등의 기능을 수행함.

서버 실행

app.listen(8080, function(){
    console.log('Server is running on port 8080');
});
  • app.listen(8080, ...) : 서버를 포트 8080에서 실행시킴.
  • 포트 8080은 클라이언트(브라우저 등)가 이 서버에 접속할 때 사용하는 주소의 포트 번호.
  • 두 번째 인자는 콜백 함수로, 서버가 성공적으로 실행될 때 콘솔에 메시지를 출력함.

라우터 설정

app.get('/', function(req, res){
    res.send('Hello World');
});

  • 클라이언트가 /(root 경로)로 GET 요청을 보낼 경우, 서버는 "Hello World"라는 문자열을 응답함.
app.get('/hello', function(req, res){
    res.send('Hello?');
});

  • 클라이언트가 /helloGET 요청을 보낼 경우, 서버는 "Hello?"라는 문자열을 응답함.

server.js 실행

node server.js
  • node는 Node.js 런타임 실행 명령어.
  • 자바스크립트 파일을 브라우저가 아닌 서버 환경에서 실행할 수 있도록 함.
  • server.js 파일이 Node.js에 의해 해석됨.

nodemon

npm install -g nodemon
  • nodemon은 Node.js 애플리케이션을 자동으로 모니터링 하는 도구
  • 코드 파일이 변경되면, 서버를 자동으로 다시 실행해줌.
  • 일반적으로 개발 환경에서 node 대신 사용함.
  • 위의 코드에서 -g는 전역 설치라는 뜻으로, nodemon을 시스템 전체에 설치함.

nodemon 실행에 오류가 발생하는 경우

  • Window PowerShell 관련해서 관리자 권한으로 설정되지 않아 권한 문제가 발생함.
  • Window PowerShell을 관리자 권한으로 실행 한 후, 아래 명령어 입력하여 보안 정책을 변경함.
    executionpolicy
    set-executionpolicy unrestricted

HTML 입력

const express = require('express');
const app = express();

app.listen(8080, function(){
    console.log('Server is running on port 8080');
});

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});
  • HTML 파일(index.html)을 클라이언트에 응답으로 보내도록 코드를 수정함.
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Document</title>
    </head>

    <body>
        <h1>Hello World</h1>
    </body>
</html>
  • index.html이라는 파일 이름으로 파일을 저장해 줌.

  • 설정한 HTML 파일에 대응하는 내용을 브라우저에서 확인할 수 있음.