Web Application 만들기
- Express : 자바스크립트로 웹사이트 또는 API를 제작하는데 사용되는 프레임워크
- 🔗 공식 사이트 바로가기
I. 사전 준비
1. Node.js 설치 (14버전 이상)
- 컴퓨터에서 자바스크립트를 실행할 수 있도록 해줌
- 🔗 공식 사이트 바로가기
2. VS Code 설치
3. Git 설치
- 🔗 공식 사이트 바로가기
- 🔗 Git 사용법
- 🔗 Github 사용법
II. 프로젝트 시작하기
1. 프로젝트 생성
mysql-web-practice 폴더 생성 후 VS Code에서 열기
Ctrl + `로 터미널 열기
Express generator 설치 (맥의 경우 필요시 앞에 sudo 추가)
npm install -g express-generator
Express 웹 어플리케이션 시작 (Handlebars 템플릿)
express --view=hbs .
필요 모듈 설치
npm install
2. nodemon - 저장시 자동 재실행 모듈
nodemon 설치 (맥의 경우 필요시 앞에 sudo 추가)
npm install -g nodemon
package.json > scripts에 추가
"start-w": "nodemon ./bin/www"
프로젝트 실행해보기
npm run-script start-w
🔗 localhost:3000 접속
3. 기본 사이트 구성
views/layout.hbs
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='stylesheet' href='/stylesheets/style.css' />
<title>{{title}}</title>
</head>
<body>
{{{body}}}
</body>
</html>
🔗 /public/stylesheets/style.css
views/sections.hbs
<h1>{{ title }}</h1>
<ul>
<li>
<a href="biz-simple?section=">
<span>🌎</span> 전체
</a>
</li>
{{#each sections}}
<li>
<a href="biz-simple?section={{ section_id }}">
<span>{{ icon }}</span>
{{ section_name }}
</a>
</li>
{{/each}}
</ul>
/routes/index.js 중
router.get('/', function(req, res, next) {
res.render('sections', {
title: '섹션 목록'
});
});
🔗 localhost:3000 접속
III. MySQL 사용
MySQL2 모듈 설치
npm install --save mysql2
/database/sql.js
const mysql = require('mysql2');
const pool = mysql.createPool(
process.env.JAWSDB_URL ?? {
host: 'localhost',
user: 'root',
database: 'mydatabase',
password: '12345678',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
}
);
const promisePool = pool.promise();
const sql = {
getSections : async () => {
const [rows] = await promisePool.query(`
SELECT * FROM sections
`)
return rows
},
}
module.exports = sql
/routes/index.js 중
var sql = require('../database/sql')
const sectionIcons = [
'🍚', '🍿', '🍜', '🍣', '🥩', '☕', '🍰'
]
router.get('/', async function(req, res, next) {
const sections = await sql.getSections()
sections.map((item) => {
item.icon = sectionIcons[item.section_id - 1]
})
res.render('sections', {
title: '섹션 목록',
sections
});
});
🔗 localhost:3000 접속