[Node.js] 간단히 서버 만들기

Programming/Node.js 2021. 8. 26. 14:33 Posted by 생각하는로뎅
반응형

Node.js 설치

 

1. Server 구동을 위한 express 파일 설치

 

> npm install express

added 1 package from 1 contributor and audited 1 package in 0.551s
found 0 vulnerabilities

PS C:\work\project\nodejs\test1> npm install express --save
npm WARN saveError ENOENT: no such file or directory, open '..\nodejs\test1\package.json'
npm WARN enoent ENOENT: no such file or directory, open '..\nodejs\test1\package.json'
npm WARN test1 No description
npm WARN test1 No repository field.
npm WARN test1 No README data
npm WARN test1 No license field.

+ express@4.17.1
added 50 packages from 37 contributors and audited 51 packages in 2.511s
found 0 vulnerabilities

 

 

 

2. view engine 을 위한 ejs(Embedded JavaScript templates) 설치

 

> npm install ejs

npm WARN saveError ENOENT: no such file or directory, open '..\nodejs\test1\package.json'
npm WARN enoent ENOENT: no such file or directory, open '..\nodejs\test1\package.json'
npm WARN test1 No description
npm WARN test1 No repository field.
npm WARN test1 No README data
npm WARN test1 No license field.

+ ejs@3.1.6
added 15 packages from 8 contributors and audited 104 packages in 1.969s
found 0 vulnerabilities

 

 

 

3. root / server.js 파일 생성

 

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

// 서버 listen
const server = app.listen(3000, ()=> {

    console.log("Start serer : localhost:3000");

})

// __dirname : 현재 디렉토리
// page 경로 설정
app.set("views", __dirname + "/views");

// ejs(Embedded JavaScript templates) : html에서 javascript를 같이 쓸 수 있게끔 해주는 engine 이다.
app.set("view engine", "ejs");

app.engine("html", require("ejs").renderFile);

// 라우터 설정
app.get("/", function(req, res) {
    res.render("index.html")
});

 

 

 

4. root / views / index.html 파일 생성

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <h1>Wellcom to my page</h1>
    
</body>
</html>

 

 

 

5. 서버 구동

 

> node server.js

Start serer : localhost:3000

 

 

 

6. 브라우저 접속 결과

 

Chrome browser

 

 

 

7. 폴더 구조

 

Visual Studio Code Tool

 

반응형