[nodejs]EJS사용하기-코드설명/Using EJS – Code Explanation – 2

바로 이전 포스트의 Server.js 및 test.ejs 코드 설명입니다.
This is the explanation of the Server.js and test.ejs code from the previous post.

1.모듈추가 부분(Module addition part)
– ejs와 express,path모듈을 추가합니다.
– Add ejs, express, and path modules.

const { createServer } = require('http');
const ejs = require('ejs'); //ejs
const express = require('express'); //express
const path = require('path'); //path
const app = express();
const server = createServer(app);

2.EJS 셋팅(EJS Settings)
– view engine으로 ejs를 사용하고 ejs디렉토리 이름을 ‘public’으로 지정합니다.
– Use ejs as the view engine and name the ejs directory ‘public’.

app.set('view engine','ejs');
app.set('views','./public');

3.Server static files
– express에서 사용될 폴더 위치 지정하고 이름을 public으로 지정 합니다.
– Specify the location of the folder to be used in express and name it public.

app.use(express.static(path.join(__dirname, "public")));

4.Express get
– 브라우저에서 www.yourdamin.xx:3000/test 실행시 브라우저에 Hello Wold!출력 합니다.
– When you run www.yourdamin.xx:3000/test in your browser, Hello Wold! is displayed in the browser.

const hello = "Hello world!";
app.get("/test", (req, res) => {
  res.render('test', { message:hello });
});

5.서버실행 코드
– node server.js실행시 ‘Server is running on port 3000’을 표시합니다.
– 브라우저에서 3000번포트로 접속허용 합니다.

When running ‘node server.js’ in the shell, ‘Server is running on port 3000’ is displayed.
Allow connection to port 3000 in the browser.

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

6.전체코드(full code)


//server.js --> Commonjs type
const { createServer } = require('http');
const ejs = require('ejs'); //ejs
const express = require('express'); //express
const path = require('path'); //path
const app = express();
const server = createServer(app);

// ejs settings
app.set('view engine','ejs');
app.set('views','./public');

// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, "public")));

//-----------------------------------------------

const hello = "Hello world!";
app.get("/test", (req, res) => {
  res.render('test', { message:hello });
});

//-----------------------------------------------


// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Leave a Reply

Your email address will not be published. Required fields are marked *