http = hyper text transfer protocal
여기서 hyper text 는 html을 의미함
즉, http는 html을 운반(transfer)하는 통신규약(protocal)임
http는 웹브라우저와 웹서버의 request, response Header를 이용해 데이터를 전송함
브라우저 → 서버 : request
서버 → 브라우저 : response
헤더를 볼 수 있는 방법 : 검사 > 네트워크> 헤더 > Request Header. Response Header
Response 헤더는 Set-Cookie로 Request 헤더에게 쿠키를 넘겨줌
http의 특징 2가지 :
- Connectionless 프로토콜 (비연결지향)
클라이언트가 서버에 요청(Request)을 했을 때,그 요청에 맞는 응답(Response)을 보낸 후 연결을 끊는 처리방식이다.
- Stateless 프로토콜 (상태정보 유지 안함)
클라이언트와 첫번째 통신에서 데이터를 주고 받았다 해도,두번째 통신에서 이전 데이터를 유지하지 않는다.
클라이언트 로컬에 저장되는 작은 텍스트 파일
클라이언트의 상태 정보를 로컬에 저장했다가 요청(Request)할 때 참조됨
Ex. count 실습 - 클라이언트(브라우저)가 count = 1 이란 쿠키가 포함된 요청헤더를 서버로 전송
웹서버가 count = 1을 받으면 nodejs 안에서 +1 한 후 응답헤더를 클라이언트에게 전달
⇒ 쿠키는 클라이언트의 정보를 저장했다가 요청시 헤더에 포함되어 전송된다.
express 에서 쿠키 사용 방법 : cookie-parser 미들웨어 사용
다운로드 방법 : npm install cookie-parser —save
기본 세팅 :
var cookieParser = require('cookie-parser');
app.use(cookieParser());
기본 문법 :
res.cookie('count',1);
res헤더로 set-cookie : count=1 전달
다음 실행시 req헤더에 cookie : count=1 존재
req.cookies.count;
req헤더로 받은 것 중 cookies 안의 count 값
cookie 실습 1 - count
var express = require('express');
var app = express();
var port = 3000;
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/count', function(req,res){
if(req.cookies.count){
var count = parseInt(req.cookies.count);
} else {
var count = 0;
}
count = count +1;
res.cookie('count',count); // set-cookie 설정
res.send('count : '+count);
});
app.listen(port,function(){
console.log(port+'번 포트에 연결되었습니다!!!');
}
cookie 실습 2 - myplaylist
페이지 : 메인 - song / 플레이리스트 - myplaylist
노래 클릭 → myplaylist/id 에서 쿠키 작업 수행 → myplaylist 로 리다이렉션
이외에 객체 문법 등 주의하며 복습하기
var express = require('express');
var app = express();
var port = 3000;
var cookieParser = require('cookie-parser');
app.use(cookieParser());
var songlist ={
1:{title:'Top Of The World'},
2:{title:'Last Night On Earth'}
};
app.get('/song',function(req,res){
var output='';
for(var name in songlist){
output += `<li><a href="/myplaylist/${name}">${songlist[name].title}</a></li>`
// 객체에 []연산자와 .연산자로 접근
}
res.send(`
<h1>PlayList</h1>
<ul>${output}</ul>
<a href="/myplaylist">My playlist</a>`);
})
// 링크 클릭 -> 해당 id 에 + 1 하고 myplaylist로 리다이렉트 (사용자에게 안보임)
app.get('/myplaylist/:id', function(req,res){
var id = req.params.id;
if(req.cookies.songs){
var songs = req.cookies.songs;
} else {
var songs = {};
}
if(!songs[id]){
songs[id] = 0;
// 클래스에 데이터 추가 (없던 key에 값 대입-> 새로 생성됨)
// songs 구조 : 첫번째 노래가 2번 재생 = 1:2
}
songs[id] = parseInt(songs[id]) + 1;
res.cookie('songs',songs); // Set-Cookie : songs = {}
res.redirect('/myplaylist');
});
app.get('/myplaylist',function(req,res){
var songs = req.cookies.songs;
if(!songs){ // 아무 링크도 누르지 않았을 때
res.send('Empty!');
} else {
var output = '';
for(var id in songs){
output += `<li>${songlist[id].title}(${songs[id]})</li>`
}
}
res.send(`<h1>My playlist</h1><ul>${output}</ul><a href="/song">song</a>`)
})
app.listen(port,function(){
console.log(port+'번 포트에 연결되었습니다!');
})
1) http 대신 https 사용
https 는 http에 secure socket 만 추가된 프로토콜이다.
기본 골격이나 사용 목적 등은 http와 거의 동일하지만
https는 서버와 클라이언트 사이의 모든 통신내용이 암호화된다는 차이를 가지고 있다.
2) 쿠키 값 암호화
var express = require('express');
var app = express();
var port = 3000;
var cookieParser = require('cookie-parser');
app.use(cookieParser('dsaf'));
app.get('/count', function(req,res){
if(req.signedCookies.count){
var count = parseInt(req.signedCookies.count);
} else {
var count = 0;
}
count = count +1;
res.cookie('count',count,{signed:true});
res.send('count : '+count);
});
app.listen(port,function(){
console.log(port+'번 포트에 연결되었습니다!!!');
})
var express = require('express');
var app = express();
var port = 3000;
var cookieParser = require('cookie-parser');
app.use(cookieParser('아무값이나 입력하면 key로 사용됨'));
var songlist ={
1:{title:'Top Of The World'},
2:{title:'Last Night On Earth'}
};
app.get('/song',function(req,res){
var output='';
for(var name in songlist){
output += `<li><a href="/myplaylist/${name}">${songlist[name].title}</a></li>`
}
res.send(`
<h1>PlayList</h1>
<ul>${output}</ul>
<a href="/myplaylist">My playlist</a>`);
})
app.get('/myplaylist/:id', function(req,res){
var id = req.params.id;
if(req.signedCookies.songs){
var songs = req.signedCookies.songs;
} else {
var songs = {};
}
if(!songs[id]){
songs[id] = 0;
}
songs[id] = parseInt(songs[id]) + 1;
res.cookie('songs',songs,{signed:true});
res.redirect('/myplaylist');
});
app.get('/myplaylist',function(req,res){
var songs = req.signedCookies.songs;
if(!songs){
res.send('Empty!');
} else {
var output = '';
for(var id in songs){
output += `<li>${songlist[id].title}(${songs[id]})</li>`
}
}
res.send(`<h1>My playlist</h1><ul>${output}</ul><a href="/song">song</a>`)
})
app.listen(port,function(){
console.log(port+'번 포트에 연결되었습니다!');
})