2021년 2월 11일 목요일

NodeJS, Express, Bootstrap, pug 기반 간단한 웹 서비스 개발 방법

이 글은 NodeJS, Express, Bootstrap, pug 기반 웹 서비스 개발 방법을 이야기한다. 

이 글은 NodeJS, Express, Bootstrap, pug가 무엇인지 알고 있다는 가정에서 진행한다. 각 패키지 설명은 아래 링크를 참고한다.

NodeJS, Express 기반 간단한 웹 페이지 만들기

순서는 nodejs 앱 폴더 구조를 만들고, npm package파일을 생성한다. 그리고, 코딩한다. 터미널에서 다음 절차로 따라한다.

1. 폴더를 다음과 같이 생성

mkdir expressApp
cd expressApp
mkdir views

2. Package.json 파일 생성
{
  "name" : "website-using-express",
  "version" : "0.0.1",
  "scripts" : {
    "start" : "node Server.js"
  },
  "dependencies" : {
    "express" : "latest"
  }
}

3. 패키지 설치
npm install 

4. server.js 코딩. 라우터에서 각 URL마다 해당 웹페이지를 지정함.
var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';

router.use(function (req,res,next) {
  console.log("/" + req.method);
  next();
});

router.get("/",function(req,res){
  res.sendFile(path + "index.html");
});

router.get("/about",function(req,res){
  res.sendFile(path + "about.html");
});

router.get("/contact",function(req,res){
  res.sendFile(path + "contact.html");
});

app.use("/",router);

app.use("*",function(req,res){
  res.sendFile(path + "404.html");
});

app.listen(3000,function(){
  console.log("Live at Port 3000");
});

5. Views 폴더내 index.html 파일 생성. 메뉴바를 navbar스타일로 정의. 텍스트 박스는 jumbotron스타일 사용.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Single page web app using Angularjs</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div>
<div>
<nav class="navbar navbar-inverse" role="navigation" style="padding-left:130px;">
<ul class="nav navbar-nav">
<li class="active"><a href="/">Home<span class="sr-only">(current)</span></a></li>
<li><a href="/about">About us</a></li>
<li><a href="/contact">Contact us</a></li>
</ul>
</nav>
</div>
<br/>
<div class="jumbotron"> <p>
Building information modeling (BIM) is a process supported by various tools, technologies and contracts involving the generation and management of digital ...
</p></div>
</div>
</body>
</html>

6. Views 폴더내 about.html 파일 생성
<html>
  <head>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div>
    <div>
    <nav class="navbar navbar-inverse" role="navigation" style="padding-left:130px;">
      <ul class="nav navbar-nav">
        <li><a href="/">Home</a></li>
        <li class="active"><a href="/about">About us<span class="sr-only">(current)</span></a></li>
        <li><a href="/contact">Contact us</a></li>
      </ul>
    </nav>
    </div>
    <br/>
    <div class="jumbotron">
      <p>
       it's not a tool or system. In academic, it can be traced back to the 1960s and since then it was researched and developed by various names. <a href='https://sites.google.com/site/bimprinciple/'>BIM principle</a>
      </p>
    </div>
    </div>
  </body>
</html>

7. Views 폴더내 contract.html 파일 생성
<html>
    <head>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        <div>
        <div>
            <nav class="navbar navbar-inverse" role="navigation" style="padding-left:130px;">
            <ul class="nav navbar-nav">
            <li><a href="/">Home</a></li>
            <li><a href="/about">About us</a></li>
            <li class="active"><a href="/contact">Contact us<span class="sr-only">(current)</span></a></li>
            </ul>
            </nav>
        </div>
        <br/>
        <form class="form-horizontal" role="form" style="width: 50%;">
            <div class="form-group">
                <label for="name" class="col-sm-2 control-label">Name</label>
                <div class="col-sm-10">
                <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="">
                </div>
            </div>
            <div class="form-group">
                <label for="email" class="col-sm-2 control-label">Email</label>
                <div class="col-sm-10">
                <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" value="">
                </div>
            </div>
            <div class="form-group">
                <label for="message" class="col-sm-2 control-label">Message</label>
                <div class="col-sm-10">
                <textarea class="form-control" rows="4" name="message"></textarea>
                </div>
            </div>
            <div class="form-group">
                <label for="human" class="col-sm-2 control-label">3D + time = ?</label>
                <div class="col-sm-10">
                <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-10 col-sm-offset-2">
                <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-10 col-sm-offset-2">
                <! Will be used to display an alert to the user>
                </div>
            </div>
        </form>
        </div>
    </body>
</html>

8. Views 폴더내 404.html 파일 생성
<html>
<head>
</head>
<body>
<h3>
Wrong Pages.
</h3>
</body>
</html>

9. 다음과 같이 실행하고, http://localhost:3000 에 접속한다. 화면이 보이면 성공한것이다.
npm start


PUG기반 BIM 카탈로그 블로그 만들기
앞에서 작업했던 Express, Bootstrap에 PUG를 추가한 BIM 카탈로그 블로그를 만들어본다(github code download).

1. 폴더 생성
mkdir catBIM
cd catBIM
mkdir views
cd views
mkdir includes
mkdir mixins
cd ..

2. package.json 파일 생성
{
  "name": "BIM catalog",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"    
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.21.1",
    "express": "^4.17.1",
    "pug": "^3.0.0"
  }
}

3. 패키지 설치
npm init -y
npm install express pug axios

4. index.js 코딩
const express = require("express");
const axios = require("axios");
const app = express();

app.set("view engine", "pug");  // view engine 으로 pug 형식 지정.

app.get("/", async (req, res) => {
  const query = await axios.get("https://randomuser.me/api/?results=9");
  res.render("index", { users: query.data.results });
});

const PORT = 3000;  // 서버 실행
app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}...`);
});

5. views/index.pug 코딩
extends layout.pug
include mixins/_thumbCard

block content
  .album.py-5.bg-light
    .container
      .row
        each user in users
          +thumbCard(user)

6. views/layout.pug 코딩
doctype html
html
  head
    title BIM Example
    link(rel='stylesheet' href='https://getbootstrap.com/docs/4.4/dist/css/bootstrap.min.css')
    style.
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }

      footer {
        padding-top: 3rem;
        padding-bottom: 3rem;
      }

      footer p {
        margin-bottom: .25rem;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }

  body
    include includes/header.pug

    main#main
      include includes/jumbotron.pug

      block content

    include includes/footer.pug
    
    script(src='https://code.jquery.com/jquery-3.4.1.slim.min.js')
    script(src='https://getbootstrap.com/docs/4.4/dist/js/bootstrap.bundle.min.js')

7. views/mixins/_thumbCard.pug 코딩
mixin thumbCard(user)
  .col-md-4
    .card.mb-4.shadow-sm
      svg.bd-placeholder-img.card-img-top&attributes({"width": "100%"}, {"height": "30"}, {"focusable": "false"}, {"role": "img"})
        title #{user.name.first} #{user.name.last}
        rect(width="100%" height="100%" fill="#55595c")
        text(x="50%" y="50%" fill="#eceeef" dy=".3em") #{user.name.first} #{user.name.last}
        img.ui.mini.rounded.image(src='https://sites.google.com/site/bimprinciple/_/rsrc/1355538518737/in-the-news/bimforum-bimtofmlaxiyagi/LAX2.PNG?height=200&width=400')
      .card-body
        .card-text #{user.location.street.number} #{user.location.street.name}
        .card-text #{user.location.city}, #{user.location.state} #{user.location.postcode}
        .card-text.mb-4 #{user.location.country}
        .d-flex.justify-content-between.align-items-center
          .btn-group
            button.btn.btn-sm.btn-outline-secondary View
            button.btn.btn-sm.btn-outline-secondary Edit
          small.text-muted 9 mins

10. views/includes/header.pug 코딩
header
  .collapse.bg-dark#navbarHeader
    .container
      .row
        .col-sm-8.col-md-7.py-4
          h4.text-white Hidden Content
          p.text-muted Until now, we look at one side of 2-dimension framework force in the various engineering information which has been designed. Consequently, the information in the framework is transformed from the original design concept.
        .col-sm-4.offset-md-1.py-4
          h4.text-white Contact
          ul.list-unstyled
            li
              a.text-white(href='#') Facebook
            li
              a.text-white(href='#') Twitter
            li
              a.text-white(href='#') Instagram
  nav.navbar.navbar-dark.bg-dark.shadow-sm
    .container.d-flex.justify-content-between
      a.navbar-brand.d-flex.align-items-center
        //- Including the svg logo
        include logo.svg
        strong BIM Example
      button.navbar-toggler.collapsed&attributes({'data-toggle': 'collapse'}, {'data-target': '#navbarHeader'})
        span.navbar-toggler-icon

11. views/includes/jumbotron.pug 코딩
section.jumbotron.text-center
    .container
        h1 BIM Example
        p.lead.text-muted The fact that the concept of BIM is now new. Of course, it's not a tool or system. In academic, it can be traced back to the 1960s and since then it was researched and developed by various names.
        p
          a.btn.btn-primary.m-2(href="#") Main call to action
          a.btn.btn-secondary.m-2(href="#") Secondary action

12. views/includes/footer.pug 코딩
footer.text-muted
  .container
    p.float-right
      a(href="#") Back to top
    p BIM example is © Bootstrap, but please download and customize it for yourself!
    p New to Bootstrap? #[a(href="https://getbootstrap.com/") Visit the homepage] or read our #[a(href="https://getbootstrap.com/docs/4.4/getting-started/introduction/") getting started guide].

13. 웹서버 실행
npm start

localhost:3000에 접속하면 다음 화면을 볼 수 있다.


레퍼런스

댓글 1개:

  1. Thank you for sharing the valuable information about the Install or Upgrade Node.js. Looking for best Node JS Development Services, reach Seasia Infotech today & discuss your requirements!

    답글삭제