SNS서비스 Project 1

FrontEnd

Posted by ETHAN KIM on November 08, 2021 · 8 mins read
Node.js

1. 패키지 구조 갖추기

프로젝트 폴더 생성 후 이동, Terminal 창에 ‘npm init’으로 프로젝트 패키지 구성

package.json
$ node
{
  "name": "nodebird",
  "version": "0.0.1",
  "description": "SNS service",
  "main": "app.js",
  "scripts": {
    "start": "nodemon app",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "EthanK",
  "license": "ISC",
  "dependencies": {
    "cookie-parser": "^1.4.5",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "express-session": "^1.17.2",
    "morgan": "^1.10.0",
    "multer": "^1.4.3",
    "mysql2": "^2.3.3-rc.0",
    "nunjucks": "^3.2.3",
    "sequelize": "^6.9.0",
    "sequelize-cli": "^6.3.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.14"
  }
}


2. 서버 start 파일 구성

데이터베이스 구성 및 연동을 제외하고 Express서버 셋팅 및 미들웨어를 등록한다.

app.js
const express = require('express')
const cookieParser = require('cookie-parser')
const morgan = require('morgan')
const path = require('path')
const session = require('express-session')
const nunjucks = require('nunjucks')
const dotenv = require('dotenv')

dotenv.config();
const pageRouter = require('./routes/page');
const { urlencoded } = require('express')

const app = express();
app.set('port', process.env.PORT || 8001);
app.set('view engine', 'html');
nunjucks.configure('views', {
    express :app,
    watch: true,
});

app.use(morgan('dev'));
app.use(express.static(path.join(__dirname,'public')));
app.use(express.json());
app.use(urlencoded({ extended: false }));
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(session({
    resave: false,
    saveUninitialized: false,
    secret: process.env.COOKIE_SECRET,
    cookie: {
        httpOnly:true,
        secure: false,
    },
}));

app.use('/', pageRouter);

app.use((req, res, next) => {
    const error = new Error(`${req.method} ${req.url} 라우터가 없습니다.`);
    error.status = 404;
    next(error);
});

app.use((err, req, res, next) => {
    res.locals.message = err.message;
    res.locals.error = process.env.NODE_ENV !== 'production' ? err : {};
    res.status(err.status || 500);
    res.render('error');
});

app.listen(app.get('port'), () => {
    console.log(app.get('port'), '번 포트에서 대기 중');
});


3. 라우터 응답

REST 요청에 나눠 응답 res.locals에 전역으로 사용할 변수를 할당한다. profile, main, join 페이지

page.js

const express = require('express');

const router = express.Router();

router.use((req, res, next)=>{
    res.locals.user = null;
    res.locals.followerCount = 0;
    res.locals.followingCount = 0;
    res.locals.followerIdList = [];
    next();
});

router.get('/profile', (req, res) => {
    res.render('profile', { title:'내 정보 - NodeBird' });
});

router.get('/join', (req, res) => {
    res.render('join', {title: '회원가입 - NodeBird'})
});

router.get('/', (req, res) => {
    const twits = [];
    res.render('main', {
        title: 'NodeBird',
        twits,
    });
});

module.exports = router;


4. nunjucks 템플릿엔진 serve

npm start 실행 시 nodemon app.js 실행

main.html


join.html