반응형
[package.json]
{
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2",
"sequelize": "^6.31.1",
"sqlite3": "^5.1.6"
}
}
[index.js]
var express = require('express');
var app = express();
let comments = []; //data 저장 (임시 db)
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');
const User = sequelize.define('User', {
// Model attributes are defined here
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
// allowNull defaults to true
}
}, {
// Other model options go here
});
// `sequelize.define` also returns the model
console.log(User === sequelize.models.User); // true
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
// set the view engine to ejs = ejs라는 view engine을 이용할 것
app.set('view engine', 'ejs'); //views라는 폴더에 꼭 들어가있어야해
// use res.render to load up an ejs view file
// index page
app.get('/', function(req, res) {
// res.render('index', { num: 5 });
res.render('index', { comments: comments });
});
app.post('/create', function(req, res) {
// console.log(req.query)
console.log(req.body)
const { content } = req.body
comments.push(content)
console.log(comments);
res.redirect('/')
// res.send('hi');
})
// about page
app.get('/about', function(req, res) {
res.render('about');
});
app.listen(8080);
console.log('Server is listening on port 8080');
views -> [index.ejs]
<!DOCTYPE html>
<html lang="en">
<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">
<title>Document</title>
</head>
<body>
<h1>댓글 목록</h1>
<ul>
<% for (comment of comments) { %>
<li><%= comment %></li>
<% } %>
</ul>
<hr>
<form action="/create" method="post">
<input type="text" id="lname" name="content"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
반응형
'즐거운 웹 개발' 카테고리의 다른 글
[React.js]1. Frontend 기본 구조 생성 + TailWindCSS (2) | 2024.01.09 |
---|