CCTV_ver_2.2. 로그인 기능 추가 및 세션관리, 차트 제공, Fetch API사용

3 minute read


과제 목표

Ajax의 Jquery 대신 Fetch API로 수정
조회한 데이터 chart로 출력 추가
로그인 기능 추가 / session 관리


image
➡ 위 이미지를 클릭하면 Repository로 이동합니다.


Project file view

mainPage.ejs에 있는 함수 파일을 기능별로 분리시켜 가독성을 높임

image


Fetch API를 사용하여 서버와 통신

by. 서현, 가희

기존에 사용했던 ajax 방식에서 fetch방식으로 수정.

1. 서버로 요청만 하는 경우

//데이터 새고로침 (part/refresh.ejs)
function refreshData() {
  const config = {
      method: "post"
  };
  fetch('/mainPage/refreshData', config)
    .then(res => res.json())
    .then(data => {
      console.log("refreshed!", data);
      $('#startDate').text(data.end_date);
      $('#endDate').text(data.end_date);
      $('#peopleNum').text(data.people);
      $('#vehicleNum').text(data.vehicle);
    })
    .catch(error => console.log(error))
      }

2. 서버로 값을 전달하여 요청하는 경우

//기간조회 입력 후 제출처리 (part/sumData.ejs)
function selectDate() {
    const config = {
        method: "post",
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            startDate: $("#selectStartDate").val(),
            endDate: $("#selectEndDate").val()}) //값 전달
    };
    fetch('/mainPage/dateSelect', config)
      .then(res => res.json())
      .then(data => {
        $('#sumPeople').text(data['sum(people)'])
        $('#sumVehicle').text(data['sum(vehicle)'])
      })
      .catch(error => console.log(error))
  }




조회한 데이터 Chart로 출력

by. 가희

차트

image

Code 자세히 보기
    // 시작시간,종료시간을 지정하고, 수신한 데이터를 그래프와 테이블로 표시
    function showDataTable() {

      const config = {
          method: "post",
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
              startDate: $("#table_s_time").val(),
              endDate: $("#table_e_time").val()})
      };
      fetch('/mainPage/tableDatetimeSelect', config)
        .then(res => res.json())
        .then(json => {
          $(function () {
          $(document).ready(function() {
              Highcharts.setOptions({
                  global: {
                      useUTC: false
                  }
              });
          });
          var chart;
          //시작시간 받아오는 함수
          var getDay = function() {
              var data = [];
                     for (i=0; i < json.length; i++) {
                          data.push(
                              json[i].start_date
                          );
                      }
                      console.log(data);
                      return data;
          };
          //차트 각종 설정
          $('#container').highcharts({
              chart: {
                  type: 'spline'

              },
              title: {
                  text: 'DATA GRAPH',
                  x: -20
              },
              xAxis: {
                  type: 'datetime',
                  categories:getDay(),
              },
              yAxis: [{
                  title: {
                      text: 'People'
                  },
                  plotLines: [{
                      value: 0,
                      width: 1,
                      color: '#808080'
                  }]
              },
              {
                  title: {
                      text: 'Vehicle'
                  },
                  plotLines: [{
                      value: 0,
                      width: 1,
                      color: '#808080'
                  }]
              }],
              tooltip: {
                  formatter: function() {
                          return '<b>'+ this.series.name +'</b><br/>'+
                          Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
                          Highcharts.numberFormat(this.y, 2);
                  }
              },
              legend: {
                  enabled: false
              },
              exporting: {
                  enabled: false
              },
              series: [{
                  name: 'People data',
                  data: (function() {
                      // generate an array of random data
                      var data =[];
                      for (i=0; i < json.length; i++) {
                          data.push(
                             json[i].people
                         );
                      }
                      console.log(data);
                      return data;
                  })()
               },
               {
                  name: 'Vehicle data',
                  data: (function() {
                      // generate an array of random data
                      var data = [];
                     for (i=0; i < json.length; i++) {
                          data.push(
                              json[i].vehicle
                          );
                      }
                      return data;
                  })()
              }]
          });
       //수신한 데이터를 테이블로 표시
      $("#table_body").empty();
          //build Table
      var table = document.getElementById('table_body');
      for (var i=0; i < json.length; i++)
      {
          var row = `<tr>
              <td>${json[i].start_date}</td>
              <td>${json[i].end_date}</td>
              <td>${json[i].people}</td>
              <td>${json[i].vehicle}</td>
              </tr>`
          table.innerHTML += row
      }

          })
        })
        .catch(error => console.log(error))
      }




로그인 페이지 생성 및 세션 관리 추가

by. 태훈

login_page

1. 로그인페이지

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Login Page</title>
    </head>
    <body>
        <h1>Login Page</h1>
        <form method="post" action="/login">
            아이디 : <input type="text" name="userId"/><br/>
            비밀번호 : <input type="password" name="userPw"/><br/>
            <input type="submit" value="로그인" />
        </form>
    </body>
</html>

2. 세션 미들웨어로 객체 생성

app.use(session({
    key: 'sid',
    secret: 'secret',
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 10 * 60 * 1000 // 쿠키 유효기간 10분
    }
}));

3. 로그인 인증 기능

app.get('/', (req, res) => {
    res.redirect('/login');
});

app.get('/login', (req, res) => {
    let session = req.session;
    if (session.email) {
        res.redirect('/mainPage');
    } else {
        res.render('./loginPage.ejs');
    }
});

app.post('/login', (req, res) => {
    console.log(req.body.userId);
    var sql = 'select * from user_info where user_id = ?'
    conn.query(sql, [req.body.userId], (err, row) => {
        if (err) {
            console.log(err);
        } else {
            if (row.length == 0) {
                res.write('<script>alert("Wrong ID. Please check the ID"); history.back();</script>');
            } else {
                if (row[0].user_pw != req.body.userPw) {
                    res.write('<script>alert("Wrong Passward. Please check the Passward"); history.back();</script>');
                } else {
                    req.session.email = req.body.userId;
                    res.redirect('/mainPage');
                }
            }
        }
    });
});
  • 초기에 login 영역으로 진입되도록 함
  • 사용자로부터 입력받은 ID로 DB의 행을 SELECT하고, 입력받은 PW를 조회한 값과 비교하여 mainPage 진입을 결정
  • 10분이 되면 세션 만료 (로그인 페이지로 렌더링)

4. 로그아웃

//메인페이지 로그아웃
app.post('/mainPage/logout', (req, res) => {
    req.session.destroy();
    res.clearCookie('sid');

    res.redirect('/login');
});

Updated:

Leave a comment