HTTP

정종찬·2022년 4월 19일
0

쿠키와 세션의 차이점

일반적으로 구글검색했을때 나오는 내용은

쿠키 : 브라우저에서 저장하고
세션 : 서버에서 저장한다

그래서 뭘 저장해?

브라우저에서 데이터를 저장한다는데
브라우저는 뭔데..?

브라우저

url 과 화면렌더링
사용자가 요청한 서버의 정보를 응답하여 화면에 띄운다
특정 URL로 서버로 요청

주소창 URL파트 (request / 요청)
주소창 아래 렌더부분 (reseponse / 응답)
브라우저가 서버에 요청하여 서버로부터 응답받은 파일 혹은 데이터 저장(쿠키)

서버가 아닌 브라우저가 저장할수 있는 정보를 쿠키라고 한다.
브라우저에 입력된? 데이터를 서버에 저장하는 것을 세션이라고 한다.

쿠키 : 브라우저에 저장되는 값
세션 : 서버의 메모리를 이용하여 저정하는 값

request message
GET / HTTP / 1.1

request method
GET, POST

express
nodejs를 사용하여 서버를 쉽게 구성할수 있게 만들어주는 프레임워크
클래스와 라이브러리의 집합체이다

브라우저가 서버와 통신할때 메시지 텍스트들을
string.split(' ')을 사용하여 문자열을 배열로 바꿔서 받아쓴다

컴파일에러와 런타임에러

컴파일 에러
런타임전에 아예 에러를 표출하여 실행이 안된다
오타
컴파일시 발생하는 에러

런타임 에러
컴파일에는 문제가 없었지만 실제 구행시 발생하는 에러

cors 예제

cors 에러 : 다른주소의 정보를 가져올때
브라우저에서 서로 정보가 다르기에 보안상의 이유로 차단한다

서버 1개 동기통신
리퀘스트 -> 스레드 최종리스폰스 블락상태
단점 리소픈스 지연되면 마냥기다려서 문제가 된다

비동기통신 리퀘스트 -> 백그라운드 보낸상태
다른일을 처리하면서 또 다른 리퀘스트를 대기
단점 순서를 보장하지않는다 작업순서가 꼬일수 있다
리스폰스의 처리결과를 보장받고 처리해야하는 서비스에는 부적합

언제 동기?
데이터싱크가 중요한경우 블록체인정보

언제 비동기?
화면에 바로 갱신이 필요한
유저에게 빠른 피드백이 빨리 필요할때

npm install cors
이 부분들 해결할 수있게 도와주는 모듈(라이브러리)이다

back/views/index.html

<!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>HelloWorld</title>
</head>
<body>
    HelloWorld
</body>
</html>
back/server.js

const express = require('express')
const nunjucks = require('nunjucks')
const app = express()

app.set('view engine', 'html')
nunjucks.configure('views',{
    express:app,
})

app.get('/',(req, res) => {
    // console.log(req.headers)
    // res.setHeader('name', 'jch')
    // res.setHeader('Set-Cookie', 'token=true') // 브라우저에 데이터를 저장하는게 쿠키 쿠키파서 쿠키를 간단하게 하는 라이브러리
    res.render('index')
})

// let session = 'token=true' // 서버에서 데이터를 저장하는게 세션
app.post("/getCookie", (req,res) => {   
    /*const [name, value] = req.headers.cookies.split('=')
    console.log(name,value)*/
     // true 주면 누구나 허용
     res.setHeader('Access-Control-Allow-Origin','http://localhost:4000')
     // 어떤 메서드만 허용할거냐
     res.setHeader('Access-Control-Allow-Methods','POST, GET, OPTIONS, DELETE')
     // 쿠키 공유까지 허용
     res.setHeader('Access-Control-Allow-Credentials','true')
     // 헤더 Context-type
     res.setHeader('Access-Control-Allow-Headers','Content-type')
     res.setHeader('Set-Cookie','token=true')
     res.send('test getCookie')
 
})

app.listen(3000,() => {
    console.log(`server start`)
})
cors 사용 예제
const express = require('express')
const app = express()
const nunjucks = require('nunjucks')
const cors = require('cors')
const cookieParser = require('cookie-parser')


app.set('view engine','html')
nunjucks.configure('views',{
     express:app,
 })

 app.use(cookieParser())

 app.use(cors({
     origin:['http://localhost:4000'],
     credentials: true
 }))

 app.get('/',(req,res)=>{
     res.render('index')
 })

 app.post('/getCookie',(req,res)=>{
//     // res.setHeader('Access-Control-Allow-Origin','http://localhost:4000')
//     // res.setHeader('Access-Control-Allow-Methods','POST, GET, OPTIONS, DELETE') // methods 사용여부
//     // res.setHeader('Access-Control-Allow-Credentials','true')
//     // res.setHeader('Access-Control-Allow-Headers','Content-type')


     res.setHeader('Set-Cookie','token=true')
     res.send('cookie~?')
 })

 app.get('/cookieParser',(req,res)=>{
    res.cookie('token2','true')
    res.send('cookieparser?')
 })

 app.listen(3000,()=>{
     console.log('server start')
})

넌적스(nunjucks)

html의 렌더링을 도와주는도구 빠르게 ui를 구현 가능하다

엑시오스(axios)

Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 뷰에서 권고하는 통신라이브러리

// for GET
axios.get('your_url', {withCredentials: true});
//for POST
axios.post('your_url', data, {withCredentials: true}); 
//for PUT
axios.put('your_url', data, {withCredentials: true}); 
//for DELETE
axios.delete('your_url', data, {withCredentials: true});

// data는 특별한 사항 아니면 null을 줘야 오류가 발생하지 않는다

요청 method에 따라서 받는 인자가 다르다
{withCredentials: true} 은 쿠키를 요청에 포함하기 위해서 주는 옵션값

front/views/index.html

<!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>
    <script type="text/javascript" src="https://unpkg.com/axios@0.26.1/dist/axios.min.js"></script>
    <script type="text/javascript">
        function init() {
            axios.post('http://localhost:3000/getCookie', null,
            {                
                withCredentials:'true' 
            });
        };
        init();
    </script>
</head>
<body>
    <H1>Hello Front Server!!!</H1>
</body>
</html>
front/server.js

const express = require('express')
const app = express()
const nunjucks = require('nunjucks')

app.set('view engine', 'html')
nunjucks.configure('views', {
    express:app,
})

// app.use(express.urlencoded({extended:true,}))
// app.use(express.json())

app.get('/', (req,res)=>{
    res.render('index')
})

// app.post('/getCookie', (req, res)=>{
//     console.log(req.body)
//     res.send('됨?')
// })

app.listen(4000,() => {
    console.log(`start`)
})

profile
dalssenger

0개의 댓글