본문 바로가기

블록체인 기반 핀테크 및 응용 SW개발자 양성과정 일기

[39일차 복습 및 정리] JavaScript Class, 자바스크립트 클래스, node.js express sequelize로 로그인, 회원가입, 로그아웃 등 연습

반응형

JavaScript Class란? 

 

- Class란 "특별한 함수" 

- Class란 객체를 생성하기 위한 템플릿, prototype을 이용하여 만들어짐 

- Class는 객체 지향 프로그래밍에서 특정 객체를 생성하기 위해 변수와 method를 정의하는 일종의 틀로, 객체를 정의하기 위한 상태 (멤버 변수) 와 매서드(함수)로 구성된다. 

 

 

Class basic frame

class Rectangle{
    constructor(height, width){
        this.height = height;
        this.width = width;
    }
}

 

 

 

 

함수 선언과 다르게 클래스 선언은 hoisting이 일어나지 않는다. 

클래스를 사용하기 위해서는 클래스를 먼저 선언해야한다. 

const a = new Rectangle(); 

class Rectangle{
    constructor(height, width){
        this.height = height;
        this.width = width;
    }
}

 

 

 

 

 

 

 

클래스 선언 먼저 하고 사용 가능 

class Rectangle{
    constructor(height, width){
        this.height = height;
        this.width = width;
    }
}

const a = new Rectangle(); 

 

 

 

 

 

 

 

 

 

 

 

============================================================================

 

 

join 부분 

 

 

 

 

 

login 부분 

 

views-user - login.html 작성

login.html

<form method="post" action="/user/login_check">
    <table>
        <tr>
            <td>아이디</td>
            <td><input type ="text" name = "userid"></td>
        </tr>
        <tr>
            <td>패스워드</td>
            <td><input type ="text" name = "username"></td>
        </tr>
    </table>
    <input type="submit" value="로그인하기">
</form>

routers - user - index.js 추가 

const express = require('express');
const router = express.Router();
const userController = require('./user.controller')

router.get('/join', userController.join)
router.get('/login', userController.login)
router.get('/info', userController.info)
router.post('/join_success', userController.join_success)
router.post('/login_check', userController.login_check)

module.exports = router; 

routers - user - user.controller.js 추가

let login_check=(req,res)=>{
    res.redirect('/')
}



module.exports = {
    join: join,
    login:login,
    info:info,
    join_success,
    login_check,
} 

 

 

npm install express-session 설치 후, server.js에 해당 코드 입력 

const session = require('express-session')


app.use(session({
    secret:'aaa',
    resave:false,
    saveUninitialized:true,
}))

 

session - server측에서 저장

- login인의 유지 -> server에서 내가 로그인한 id, 정보 등을 계속 가지고 있어서 값을 get, post로 끊임없이 안넘겨줘도 된다. 

 

cookie - 사용자 측에 저장 / data가 brower, 브라우저에 저장됨 

cookie 사용 예제 

ex) 장바구니 (회원가입 안하고 장바구니에 넣고 다른거 보다가 돌아왔을 때 아직 장바구니에 있는 것처럼) 

ex) 팝업 닫기, 팝업창 띄웠는데 일주일 동안 다시보지 않기 

 

- 보안성이 취약 - 데이터 조작, 수정, 삭제가 가능 

- 날아가도 좋은DATA들은 쿠키로 만들어도 괜찮다.

 

session & cookie 함께 쓰인 경우

ex) 자동 로그인 

 

Login은 session으로 만들 예정 (민감한 정보일 수록)

 

 

 

 

routers-user - user.controller.js

let login_check= async (req,res)=>{
    let userid=req.body.userid;
    let userpw = req.body.userid;
    
    let result = await User.findOne({
        where:{userid,userpw}
    })
 
    req.session.uid=userid;
    req.session.isLogin = true;
    console.log(req.session);

    res.direct('/')
}

req.session이 무엇인가해서 console.log찍어보니

req.session 안에는 cookie라는 속성이 있다 . session에 uid, islogin 라는 속성값과 그 안에 userid, true value를 넣어준다. 

 

islogin 속성은 개발자가 현재 로그인 상태가 true or false인지 편하게 구분하려고 만들어 놓은 것 

위와 같이 session 하면 JS파일 말고 server에 공통적으로 쓰는 변수가 되는 것

 

 

 

 

routers - main - main.controller.js

let main = (req,res) =>{
    res.render('index.html',{
        userid:req.session.uid,
        isLogin:req.session.isLogin,
    })
    console.log(userid, isLogin);
}

module.exports.main=main;

 

 

요 부분이 잘 이해가 안갔는데 맨 처음 '/'을 받았을 때는 userid, isLogin의 값이 undefined로 나온다. 

login_check 부분에서 req.session에 uid, isLogin value를 새로 추가하고 -> redirect '/'로 했다. 이 때 req.session 이라는게 생기는 것 같다. 

 

 

 

views -index.html

{% if isLogin %} <!-- if true -->
    {{userid}}님 환영합니다. <br/>
    <a href="#" >로그아웃</a>
{% else %}
<a href = "/user/join">회원가입</a>
<a href = "/user/login">로그인</a>

{% endif %}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

=========================================================================

 

 

 

 

 

 

연습

- 일반 함수에 객체 만들기 

function Person(name,age){
    this.name=name;
    this.age=age;
}

let emily = new Person('emily', 20); 

 

함수 Person에 인자값 name, age 두개가 있다. 

this = 본인 fucntion을 말함 

본인의 바로 아래 속성에 name, age를 붙임 

 

객체를 계속 생성해줘야하는 불편함 -> CLASS 가 생기게 됨 

 

 

 

 

function Person(name,age){
    this.name=name;
    this.age=age;
}

Person.prototype.getName=function(){
    return this.name;
}

Person.prototype.getAge = function(){
    return this.age; 
}

 

 

 

Person 이라는 함수의 prototype 에 

getName, getAge method가 들어감 

 

 

 

 

 

 

 

 

 

 

 

 

 

함수는 constructor가 있지만 객체는 없다. 

 

CLASS 

class Person{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
}

let emily = new Person('emily', 20); 

 

 

이번에는 class로 똑같이 만들어주기 

class를 쓸 때는 constructor와 함께 써주기 

 

 

 

 

 

 

 

 

class Person{
    constructor(name,age){
        this.name=name;
        this.age=age;
    }

    getName = function(){
        return this.name;
    }

    getAge = function(){
        return this.age;
    }

    setName = function(_name){
        this.name = _name;
    }
}

let a = new Person('emily', 20);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

function Person2(name,age){
    this.name=name;
    this.age=age;
}

Person2.setName = function(){  //정적 / static
    return 'a';
}

Person2.prototype.getName=function(){
    return this.name;
}

Person2.prototype.getAge=function(){
    return this.age;
}

let a = new Person2('emily', 20);

 

Person2.setName = f(){} 이 부분은 정적 (static) method라 객체에게 해당 속성을 물려주지 않는다. (객체 변환이 안됨)

 

static = 함수인 상태일 때 사용가능한 형태, 객체로는 사용 되지 않음 

 

 

 

 

 

 

 

 

 

 

class Person2 {
    constructor(name,age){
        this.name = name;
        this.age = age;
    }

    static setName = function(){  //Person2.setName = func~ 
        return 'a';
    }

    getName = function(){       //Person2.prototype.getName = ~ 
        return this.name;
    }

    getAge = function(){
        return this.age;
    }
}

let b = new Person2('emily', 20);

 

static 인 method는 객체에게 전달되지 않는다 

static method인 setName은 . dot을 찍고 바로 사용이 가능하다 

 

즉, new라는 객체 생성자를 만들지 않고 사용할 때 static을 쓴다. 유동적인 객체를 만들지 못해서 정적method라고 불린다. 

 

 

 

 

 

 

 

 

 

 

 

 

------------------------------------------------ 부모, 자식 CLASS 만들어 보기 -----------------------------------------------

 

상속 = 두 개의 내용을 합쳐서 보여주겠다. 

 

class Person{                            //부모 
    constructor(name,age){
        this.name = name;
        this.age=age;
    }
}

class Action extends Person{              //자식 extends (속성을 받는다 ) from Person
    run = function(){
        console.log('run');
    }
}

a = new Action ();

 

 

 

 

 

 

 

 

 

class Person{
    constructor(name,age){
        this.name = name;
        this.age=age;
    }
}

class Action extends Person{
    run = function(){
        console.log('run');
    }
}

a = new Action ('emily', 20);

 

 

 

 

 

 

 

 

 

 

class Person{
    constructor(name,age){
        this.name = name;
        this.age=age;
    }

    setName = function(){
        return this.name;
    }

}

class Action extends Person{}

a = new Action ('emily', 20);

 

 

 

 

 

 

 

 

 

 

 

class 쓸 때 꼭  constructor를 만들어 줘야 했는데 자식 class의 경우 constructor를 안써줘도 된다. 만약 쓰게되면 아래와 같은 오류가 뜬다. 

class Person{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
}

class Action extends Person{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }

    run = function(){
        console.log('run');
    }
}

a = new Action('emily', 20);

 

부모와 자식간의 constructor를 맞춰줘야 한다. 위의 코드처럼 자식 class에 constructor를 쓰고 싶다면 super을 사용해야한다. 

 

 

 

class Person{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
}

class Action extends Person{
    constructor(name,age){
        super(name,age)
    }

    run = function(){
        console.log('run');
    }
}

a = new Action('emily', 20);

 

 

super - 부모의 정적 method 내용을 가져온다.  

 

 

 

 

 

class Model{
    constructor(){

    }
    
    static init(){
        return '악'
    }

    getName(){
        return this.name;
    }
}

class User extends Model{
    static init(){
        return super.init()
    }
}

let a = User.init();

static은 new로 접근할 수 없다. 바로 . 을 찍고 사용하기 

 

 

 

 

 

 

 

 

질문 

아래 차이 

let logout = (req,res)=>{
    delete req.session.uid;
    delete req.session.isLogin;

    res.redirect('/');
    
}
let logout = (req,res) =>{
    delete req.session.isLgin;
    delete req.session.uid;

    req.session.save(()=>{
        res.redirect('/');
    })
}

 

 

이유 : session 안에 cookie가 함께 있어서 save해줘야함! 

 

 

d-> login인 후 f5 눌러도 로그인 되어 있음. 

session - server에 쿠키랑 연결되서 저장되어 있음. 

cookie -client마다 가지고 있는 값 

 

쿠키 삭제하면 -> 로그인이 풀림 

 

반응형