https://expressjs.com/ko/starter/generator.html

Express 애플리케이션 생성기를 통한 설치

> npm install express-generator -g
> express --view=pug myapp

> cd myapp
> npm install

    - 앱시작
> set DEBUG=myapp:* & npm start

    - 브라우저로 확인
http://localhost:3000/


//-------------------------------------
    - 서비스 포트 변경
https://stackoverflow.com/questions/13333221/how-to-change-value-of-process-env-port-in-node-js

process.env.PORT 값 변경 방법
    - 환경변수 변경, 시작하는 배치파일에 설정한다.
set PORT=1234


//-------------------------------------
소스 수정시 자동으로 서버 재시작하도록 설정
> npm install nodemon -g

    - package.json 파일 수정
"scripts": {
        "start": "nodemon ./bin/www",


//-------------------------------------
controller 사용
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes

- 모듈 설치
> npm install express-async-handler


    - controllers/userController.js 파일 생성
const asyncHandler = require("express-async-handler");

exports.user = asyncHandler(async (req, res, next) => {
    res.render('user/user', { // PUG 경로
        title: 'user'
    });
});


    - routes/index.js 수정
const con_user = require("../controllers/userController");
router.get('/user', con_user.user);



//-----------------------------------------------------------------------------
PUG template engine (템플릿 엔진)
https://expressjs.com/en/resources/template-engines.html
https://github.com/pugjs/pug
https://pugjs.org/api/getting-started.html


- vscode 용 PUG 포멧터 적용
extension에서 'pug (jade) formatter'를 설치한다.


- js 함수 실행 방법
    script.
        console.log(new Date().getTime())


//-------------------------------------
- node.js 함수 실행 방법
https://stackoverflow.com/questions/62738791/how-to-execute-a-nodejs-function-in-pug

    - route 수정
router.get('/quiz0', function (req, res, next) {
    res.render('quiz/quiz', {
        title: 'quiz'
funcName: funcName // PUG에서 호출할 함수(클래스) 지정
    });
});


    - PUG 파일에서 호출
script !{funcName}


//-------------------------------------
미들웨어와 전역변수 설정
    - app.js 파일 수정
    - 위치 주의! 라우트 전에 지정
app.use(function (req, res, next) {    
    res.locals.g_val = '전역 변수';
    next()
});


반응형
Posted by codens