728x90

만들기에 앞서서 

이거 먼저 만들어놔야

어떤 모듈 들어가있는지 확인할 수 있어

 

만드는 법  npm init

 

수업 듣다가 놓쳐서 에러뜨길래 물어보니까

 

 

 

스크립트에 

"start" : "nodemon app"

으로 바꿔줘야 했고

 

scripts 부분에 start 속성 잊지 말고 넣어야~!!

nodemon app을 하면 app.js를 nodemon으로 실행한다는 뜻이야  

 

코드 수정하면 노드몬이 서버 자동으로 재시작함 콘솔에서 rs 입력해서 수동으로 재시작할 수 있어

(개발용으로만 하는거 권장)

 

 

 

익스프레스 쓸거니까 밑에 애들깔아줘야 저렇게 들어가는 거임

 

npm i express

npm i -D nodemon

npm i morgan cookie-parser express-session dotenv body-parser

 

한번에 여러 개 깔 수 있음 (밑줄친건 안깔았나? 보면 없어서 안깔은거같기도 하고..)

 

원래 로그인페이지만 따라 만들고

과제로 다른 페이지로 넘어가는 거 함. 

 

일단 결과물

 

 

 

 

로그인 페이지 login.html

<!DOCTYPE html>
<html lang="ko">
  <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>
  </head>
  <body>
    <h1>Login Page</h1>
    <hr />
    <form method="post">
      <table>
        <tr>
          <td><label>UserName</label></td>
          <td><input type="text" name="login" /></td>
        </tr>
        <tr>
          <td><label>Password</label></td>
          <td><input type="password" name="password" /></td>
        </tr>
      </table>
      <input type="submit" name="" />
    </form>
  </body>
</html>

 

 

메인 페이지 main.html

<!DOCTYPE html>
<html lang="ko">
  <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>메인페이지</title>
  </head>
  <body>
    <form method="POST">
      <h1>메인페이지</h1>
      <button name="loginpage" value="login-page">로그인페이지</button>
      <button name="naver" value="naver-page">검색페이지</button>
    </form>
  </body>
</html>

 

 

app.js

const express = require("express");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const fs = require("fs");
const app = express();
const port = 3001;

//미들 웨어 설정
app.use(morgan("dev"));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));

//라우터 설정
// app.get("/", (req, res) => res.send("Hello World"));
//들어가서 뜨는 로그인페이지 만약 쿠키들어있으면 성공 뜸
// app.get("/", (req, res) => {
//   if (req.cookies.auth) {
//     res.send("<h1>Login Success</h1>");
//   } else {
//     res.redirect("/login");
//   }
// });
// //메인페이지 추가해봄
app.get("/", (req, res) => {
  if (req.cookies.auth) {
    res.send("<h1>Login Success</h1>");
  }

  // fs.readFile("main.html", (error, data) => {
  //   res.send(data.toString());
  // });
  else {
    // res.redirect("/login");

    //send는 한번만 쓸수 있어서..end처럼끝내버리는거였음 그래서 밑에또부를때충돌남!!
    //여러개쓰고 싶으면 write
    //그거뿐만 아니라 불러올때 충돌나는것도 있음..
    fs.readFile("main.html", (error, data) => {
      res.send(data.toString());
    });
  }
});

app.post("/", (req, res) => {
  if (req.body.loginpage) {
    console.log(req.body);
    res.redirect("/login");
  } else req.body.naver;
  {
    res.redirect("https://www.naver.com/");
  }
});

//html페이지로
app.get("/login", (req, res) => {
  fs.readFile("login.html", (error, data) => {
    res.send(data.toString());
  });
});
//단순페이지요청(클라이언트가ㅏ요청한걸로 쿠키생성)
app.post("/login", (req, res) => {
  //쿠키생성
  let login = req.body.login;
  let password = req.body.password;
  console.log(login, password);
  console.log(req.body);
  if (login == "rint" && password == "1234") {
    res.cookie("auth", true);
    res.redirect("/");
  } else {
    res.redirect("/login");
  }
});

app.listen(port, () => console.log("example app listening on port"));

 

 

 

콘솔에서

cd 폴더주소

npm start

 

하면 

콘솔 넣은거 example app listening on port 잘 뜸

 

port 값 3001로 할당해놔서 들어가면

뜬다! 

 

버튼 두개 만들어놓은 이유가 button 눌렀을 때 name 값 잘 보내와지는지 볼라고

메인페이지 일때 

 

만약

localhost:3001/ 일때

요청.바디에 name=loginpage 이면

응답. 다시지시. localhost:3001/login

 

그것도 아니면 

요청.바디에.naver이면

응답. 다시지시.링크

 

 

로그인 페이지 넘어오면 

 

내가 get post 차이가 뭘까 에러날때마다 

다같이 얘기했음 이것도 찾아서 정리해봐야겠다

 

암튼 내가 이해한거는  

/login 일때

fs.readFile 이거는 파일 읽어서 불러오고 띄우고 

응답으로 res.send (express에서는 이거 사용)

 

 

요청.바디에.login을 login에 할당

할당하고

만약 input의 name=login이랑 정한 값이랑 같으면

응답.특정 쿠키를 만들어서

응답. "/"로 다시 불러와

 

그거 아니면

응답."/login" 불러와

 

 

 

설정한 값 잘 넣어서

쿠키값이 가지고 응답되었어!

그래서 "/" 다시 메인페이지로 돌아왔는데

왜 글자가 뜨냐면

 

 

 

 

 

 

 

만약에 

요청.쿠키들이.auth 면

응답.글자로~

 

이거 넣어서 임.

 

사실 처음에 잘되다가 

[nodemon] app crashed - waiting for file changes before starting...

 

다시 메인페이지, 버튼 두개 있는 창 띄우고 싶어서쿠키값을 오른쪽에서 삭제했는데에러가 막뜨는거야 

 

 

컨트롤 C해서

npm start

 

다시 구동했는데 됐다가 안됐다가...에러 자꾸 뜸

 

 

 

redirect를 많이해서 그런가 했는데 

위에 코드에도 적었지만

 

 

res.send 때문이었음

이게 응답과 동시에 끝내줘서 다음 동작에 안넘어가는 거야

 

그리고 원래 

 

  fs.readFile("main.html", (errordata=> {

      res.send(data.toString());

    });

 

이게 else안에 있는게 아니라 "/" 일때 맨 위에 있었고 그다음에 if였음

 

메인페이지 띄우라는 거랑

쿠키값 있을때 h1 글자창 띄우라는 거랑 충돌 났나봐

 

그래서 else 안에 넣어준거임

res.send도 하나만 쓸 수 있어서 if else 안에 넣어주고...

 

 

 

app.get

app.post 차이

 

 

res.send res.write 차이 궁금~

728x90

+ Recent posts