1. basic
//basic setup
const express=require('express');
const bodyParser = require('body-parser');
const app = express();
app.get("/",function(req, res){
//send sth back to the browser as a response
res.send("Hello");
});
app.listen(3000,function(){
console.log("Server started on port 3000");
})
2. templating
: We're using ejs
-after installing ejs in terminal, add these to the basic js codes
app.set('view engine', 'ejs');
//just below declaring app
app.get('/', (req, res) => {
res.render('index', {foo: 'FOO'});
}); //helps to render a particular page(here, "index.ejs")
//folder "views" - view engine by default will go and look for files that you're trying to render
Add folder named "views", and make a file named list.ejs
-It'll be the base template to create all of our todo lists. Write html codes inside.
- <%= markerName %>
- marker - that tells where to place particular variable
res.render("list", {markerName: value});
//express is going to look inside "views" folder,
//and it'll look for a file called "list" and has the extension of ejs
//second parameter - we'll pass in javascript object which has a key-value pair
//the key here has to match whatever marker you named in "list" file
- scriptlet tag
- for control-flow(if-else, while...)
- should be added to all non-html codes
- work on line-by-line basis
<body>
<%if (kindOfDay==="Saturday"|| kindOfDay ==="Sunday"){%>
<h1 style="color: purple"><%=kindOfDay%> To-Do List</h1>
<%}else{%>
<h1 style="color: orange"><%=kindOfDay%> To-Do List</h1>
<%}%>
</body>
app.get("/",function(req, res){
var today = new Date();
var currentDay=today.getDay();
var day="";
// if( currentDay==6 || currentDay==0){
// day="Weekend";
// }else{
// day="Weekday";
// }
switch(currentDay){
case 0: day="Sun"; break;
case 1: day="Mon"; break;
case 2: day="Tues"; break;
case 3: day="Wednes"; break;
case 4: day="Thurs"; break;
case 5: day="Fri"; break;
case 6: day="Satur"; break;
}
day+="day";
res.render("list", {kindOfDay: day});
//express is going to look inside "views" folder, and it'll look for a file called "list" and has the extension of ejs
//second parameter - we'll pass in javascript object which has a key-value pair
//the key here has to match whatever you put in list file
res.sendFile(__dirname+"/index.html");
});
submit 버튼을 통한 입력한 데이터 받아오기 + 사용
** list.ejs
<form class="add-list" action="/" method="post">
<input type="text" name="newItem" placeholder="tell me what to do">
<button type="submit" name="button">Add</button>
</form>
** app.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}));
app.post("/",function(req,res){
var item=req.body.newItem;
console.log(item);
});
입력받은 것을 추가하기
- (X)
** list.ejs
<ul>
<li>Buy FOOD</li>
<li>Cook FOOD</li>
<li>Eat FOOD</li>
<li><%= newListItem %></li>
</ul>
** app.js
app.post("/",function(req,res){
var item=req.body.newItem;
res.render("list",{newListItem: item});
});
>> 이렇게 하면 값이 없는 상태인데 표시하라고 뜨니까 오류남
- (O)
주먹구구 식이긴 하지만...
**list.ejs
<ul>
<%for(var i=0; i<newListItem.length;i++){%>
<li><%= newListItem[i] %></li>
<%}%>
</ul>
**app.js
var items=["Buy Food","Cook Food", "Eat Food"];
app.set('view engine', 'ejs');
//just below declaring app
app.use(bodyParser.urlencoded({extended:true}));
app.get("/",function(req, res){
var today = new Date();
var options={
weekday: "long",
day: "numeric",
month:"long"
};
//region needed as a parameter
var day=today.toLocaleDateString("kr-KR",options);
res.render("list", {kindOfDay: day, newListItem: items});
res.sendFile(__dirname+"/index.html");
});
app.post("/",function(req,res){
var item=req.body.newItem;
items.push(item);
res.redirect("/");
});
passing data through our server every time a new item is updated
Scope
*javascript
const로 선언되면 값을 바꿀 수 없음
- (if/else,for,while){ }안에서 선언
- var - if 밖에서도 유지됨(global) => javascript에서 유별남!
- let - local
- const - local
- function 안에서 선언
- var - local
- let - local
- const - local
- function 밖
- var - global
- let - global
- const- global
가능한 var보다 let, const 사용하기!!
css 적용
public 폴더 만들어서 거기다가 넣어놓기,
app.js 에서
app.use(express.static("public"));
express 사용선언한 곳 밑에다가 추가
입력한 페이지에 따라 다른 목록에 추가하기
route 값을 현재 위치한 곳에 따라 다르게 설정함으로써, 현재 페이지의 목록에 추가하고, 추가한 뒤에도 새 항목이 업데이트 된 현재 페이지를 유지할 수 있도록 함!
**list.ejs
<div class="box" id="heading">
<h1><%=listTitle%></h1>
</div>
<div class="box">
<%for(let i=0; i<newListItems.length;i++){%>
<div class="item">
<input type="checkbox">
<p><%= newListItems[i] %></p>
</div>
<%}%>
<form class="item" action="<%=route %>" method="post">
<input type="text" name="newItem" placeholder="New Item" autocomplete="off">
<button type="submit" name="button">+</button>
</form>
</div>
**app.js
app.get("/", function(req, res) {
let today = new Date();
let options = {
weekday: "long",
day: "numeric",
month: "long"
};
//region needed as a parameter
let day = today.toLocaleDateString("kr-KR", options);
res.render("list", { listTitle: day, newListItems: items, route:"/" });
//home route일 경우, route 변수를 "/"로 반환해줌으로써 현재 페이지를 유지하도록
});
app.post("/", function(req, res) {
let item= req.body.newItem;
console.log(req.body.list);
items.push(item);
res.redirect("/");
});
app.get("/work", function(req, res) {
res.render("list", { listTitle: "Work List", newListItems: workItems, route:"/work"});
//route 변수에 "/work"을 반환함으로써 업데이트된 work 페이지 유지하도록
});
app.post("/work",function(req,res){
let item =req.body.newItem;
workItems.push(item);
res.redirect("/work");
//work 페이지에서 post 요청 들어오면 workItems에 추가, redirect도 work페이지로 다시
})
같은 형식 유지하기
모든 파일에 붙여넣기 하는 것 대신 layout 사용하여 통일성있게 사용 가능하다!
<%- include('header'); -%> //to include 'header' file
<h1>Title</h1>
<p> texts...</p>
<%- include('footer'); -%> //to include 'footer' file
다른 사용자 생성 파일의 function 사용하기 - exports
module
** app.js
//app.js
const date=require(__dirname + '/date.js');
//사용자 생성 파일이기 때문에, dirname 사용해줘야함
** 생성한 date.js
//date.js
//date module
module.exports=getDate;
//activating the function
function getDate(){
let today = new Date();
let options = {
weekday: "long",
day: "numeric",
month: "long"
};
//region needed as a parameter
let day = today.toLocaleDateString("kr-KR", options);
return day;
}
위에서 module.exports에 getDate를 넣으면
//app.js
console.log(date);
//getDate라는 function이 있다는 걸 보여줄 뿐, 실행시키진 않음
실행시키기 위해서는 모듈명() => exports 시켜놓은 함수를 실행 가능!
//app.js
app.get("/", function(req, res) {
let day=date();
res.render("list", { listTitle: day, newListItems: items, route:"/" });
});
//모듈명()을 함으로써 exports 해놓은 함수명 실행 가능
- exports => object이기 때문에, 여러 종류 넣어두고 외부로 반출 가능!
- module.exports.getDay= getDay;
- module.exports.getYear=getYear;
- 사용시 date.getDate();하면 getDay에 할당해놓은 함수(여기서는 동명의 함수) 사용가능!
exports shortcut
module.exports.getDate = getDate;
var getDate = function(){
//getDate function contents
}
//or simply
module.exports.getDate = function(){
//getDate function contents
}
//or
exports.getDate = function(){
//getDate function contents
}
** javascript의 경우, const로 설정된 array의 경우 새로 공간 할당은 불가하지만, 이미 있는 값 변경이나 push 가능!
그냥 할당된 공간을 바꿀 수 없는거임. 내용은 바꾸기 가능!
'JavaScript' 카테고리의 다른 글
note (1) | 2022.12.04 |
---|---|
git (0) | 2022.12.04 |
basic setup routine (0) | 2022.11.25 |
jQuery (0) | 2022.11.16 |
Advanced Javascript and DOM Manipulation (0) | 2022.11.16 |