express와 pug 기본

jangky000·2020년 8월 31일
0

express 서버 띄우기

npm init
npm install --save express
node index.js

pug 사용법: JADE와 유사

https://dydals5678.tistory.com/91

// 설치
npm install pug
var express = require('express');
var app = express();

app.set('view engine' , 'pug');

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

app.listen(3000, function(){
    console.log('Example App is listening on port 3000');
})

참고 사항

// 만약 views/ 폴더가아닌 다른 폴더에서 view 템플릿을 찾을려면 
// 아래 추가 선언
app.set('views','바꿀폴더명'); 

더 간략하게 생성 방법 generator 사용

# mac에서 권한요류 발생시 sudo 추가
npm install -g express-generator 
# express가 안된다면 npx express-generator 명령으로 
express hello-express --view=pug
cd hello-express
npm install
npm start

res.locals 사용법

https://junspapa-itdev.tistory.com/13

https://rat2.tistory.com/18?category=1134650

https://stackoverflow.com/questions/35111143/express4-whats-the-difference-between-app-locals-res-locals-and-req-app-local

  • res.locals 활용하여 전역에서 사용 가능한 변수를 만들 수 있다.

    해당 미들웨어를 거친 곳 전역에서 사용 가능한 변수

  • node.js로 페이지 렌더링을 하게 되면 중복되는 값들이 있다.

    이 값들을 한꺼번에 처리할 수 있는 함수가 바로 res.locals 이다.

    해당 함수를 쓰면 렌더링시 중복되는 값들을 저장해놓고 계속해서 쓸 수 있다.

// 미들웨어: http요청 -> 미들웨어 -> 라우트 작업
var globalSession = function(req, res, next){
    // console.log(req.url); // url: /user 등이 콘솔에 표시됨
    res.locals.sessObj = {name: undefined, email: undefined};
    if(req.cookies['sid']){
        // 세션 검사
        session = sessionManager.readBySID(req.cookies['sid']);
        sessionManager.updateSession(req.cookies['sid'], configs.cookieExpireSec*1000);
        res.locals.sessObj = {name: session.name, email: session.email};
    }
    next();
}
app.use(globalSession); // 미들웨어 사용, 이것이 실행된 후에 라우팅 된다

pug 모듈화: extends와 includes

https://dydals5678.tistory.com/91

  • extends와 includes는 동작 방식이 반대적이다.
  • include는 해당 파일(부분 소드 등)의 코드를 자기 자신에게 그대로 가져온다.
  • extends는 해당 파일(레이아웃 등)을 상속 받아서 그 안에 block을 끼워 넣는다.

CSS 레이아웃 flex

flex와 flex direction row를 사용해서 그리드 형식으로 레이아웃을 잡을 수 있다.

연습: https://flexboxfroggy.com/#ko

css 모듈화

// style.css
@import "sub/header.css";
@import "sub/nav.css";

ul {
    list-style: none;
    margin: 0;
    padding: 0;
}
...

ARIA 속성(css)

ARIA (Accessible Rich Internet Applications)는 장애가있는 사람들이 웹 컨텐츠 및 웹 애플리케이션을보다 쉽게 이용할 수 있도록하는 방법을 정의합니다.

hidden 속성은 HTML5에서 새로 추가되었으며 브라우저 not에 요소를 표시합니다. aria-hidden 속성은 요소를 무시해야하는 경우

Cannot set headers after they are sent to the client

https://velog.io/@kim-macbook/Cannot-set-headers-after-they-are-sent-to-the-client

내 경우, res.end()를 함수의 끝(?)이라고 생각해서 오류가 발생했다. 
그러니까, res.end()가 return의 역할까지 하는 줄 알았는데 아니었다.
아래의 코드가 에러가 발생하는 코드였다.
res.send(), res.json(), res.render() 모두 마찬가지다.
res.send() 뒤에 next()의 코드가 오면 이러한 에러가 발생한다.
return res.send() 등으로 해결할 수 있다.

미들웨어

https://opentutorials.org/course/3370/21423

https://psyhm.tistory.com/8?category=654716 → 추천

profile
예비 웹 FE 개발자

0개의 댓글