2022.9.13.화 TIL: SQL 문풀, CTE recursive SQL, Nodejs 쿠키로 로그인 구현 with Express, 프로그래머스 직사각형 별 찍기 js

Dorito·2022년 9월 13일
0

공부 기록

목록 보기
25/71

하루 개요

Express 쿠키를 사용한 로그인
자료구조 & 리트코드/프로그래머스 문제 1개 풀기
네트워크 (ip계층) 공부
SQL 문제 풀기

여태껏 쓰던 벨로그 글 싹다 날려서 다시 적는다..
이번에는 다시 정리는 못하겠고 참고한 사이트 링크 적는 위주로 함..

리트코드 SQL 문제 풀이

# Write your MySQL query statement below

# SELECT name as Employee
# FROM Employee
# WHERE salary > (SELECT salary from Employee where )

SELECT b.name as Employee
FROM employee as a INNER JOIN  employee as b
on a.id = b.managerId
    AND b.salary > a.salary

계층형 질의 CTE 쓰는건가 쫄았는데 아니었다
기본도 잘 모르겠고 문법도 다 까먹었당...
궁금해서 찾아봄..

계층형 질의 (+ CTE, Common Table Expressions)


https://dev.mysql.com/doc/refman/8.0/en/with.html
열심히 정리햇는데... 그냥 여기 문서 보면 댄다...


http://devdoc.net/database/sqlite-3.0.7.2/lang_select.html

Express 쿠키를 사용한 로그인 구현


이미지 출처

생활코딩 이 분꺼 책 사서 보는데..nodejs 제일 기초 개념에서 도움 많이 받았으나 코드가 개인적으로 이해가 안가는 부분이 많아서
(html 파일을 왜 분리를 안하고 왜 string을 함수에 때려박는 식으로 하지... 왜 for문대신 while문 쓰지...왜 const, let 안쓰지... 왜..함수를 저렇게... x1010103394 싶어서..)
구글링이랑 공식 홈페이지 참고해서 해볼 생각임

https://www.section.io/engineering-education/client-side-auth-with-express-cookie-parser/

보고 공부함 보면서 궁금한 메서드나 키워드 검색해서 정리할 예정!

Node.js fs.createReadStream() Method

스트림 단위로 파일 읽고 쓰기 (대충 stream형태 데이터는 L7 소켓 단위에 있는 파일, 즉 로컬 파일을 쓰는거구나 ㅡ 라고 이해했다. + 로컬파일이라는 용어가 정확한지는 모르겠다. 가상메모리에 존재하는 파일들을 의미하는 것인지 .. 찾아보니 물리디스크 상의 파일, 장치들이라고 한다.)

https://nodejs.org/en/knowledge/advanced/streams/how-to-use-fs-create-read-stream/

The function fs.createReadStream() allows you to open up a readable stream in a very simple manner. All you have to do is pass the path of the file to start streaming in. It turns out that the response (as well as the request) objects are streams. So we will use this fact to create a http server that streams the files to the client. Since the code is simple enough, it is pretty easy just to read through it and comment why each line is necessary.

The createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 오류


이런 오류가 떠서 구글링 함

오류 [ERR_HTTP_HEADERS_SENT]는 서버가 클라이언트에 둘 이상의 응답을 보내려고 할 때 발생하는 흥미로운 오류입니다. 이것이 의미하는 바는 주어진 클라이언트 요청에 대해 서버가 이전에 응답 (요청 된 리소스가있는 성공 응답 또는 잘못된 요청에 대한 오류 응답)을 클라이언트로 보냈고 이제 예기치 않게 다른 응답을 보내려고한다는 것입니다.
출처

$ yarn add cookie-parser

Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
Optionally you may enable signed cookie support by passing a secret string, which assigns req.secret so it may be used by other middleware.
http://expressjs.com/en/resources/middleware/cookie-parser.html

cookieParser(secret, options)
Create a new cookie parser middleware function using the given secret and options.

  • secret a string or array used for signing cookies. This is optional and if not specified, will not parse signed cookies. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order.
  • options an object that is passed to cookie.parse as the second option. See cookie for more information.
    - decode a function to decode the value of the cookie

The middleware will parse the Cookie header on the request and expose the cookie data as the property req.cookies and, if a secret was provided, as the property req.signedCookies. These properties are name value pairs of the cookie name to cookie value.

When secret is provided, this module will unsign and validate any signed cookie values and move those name value pairs from req.cookies into req.signedCookies. A signed cookie is a cookie that has a value prefixed with s:. Signed cookies that fail signature validation will have the value false instead of the tampered value.

In addition, this module supports special “JSON cookies”. These are cookie where the value is prefixed w
ith j:. When these values are encountered, the value will be exposed as the result of JSON.parse. If parsing fails, the original value will remain.

마약같은 한글 문서.. https://jw910911.tistory.com/59 이 자료도 참고함

// 쿠키파서에 비밀키를 넣어 요청온 쿠키값이 내가 서명한 쿠키인지 파악한다.
// 암호 키를 작성하는 것에는 크게 규격이 없으며 개발자의 자유이다. 단 쉽게 유추할 수 있는 값은 사용하지 말자.
app.use(cookieParser(process.env.COOKIE_SECRET));
 
app.get('/', (req, res) => { 
   req.signedCookies // 서명 된 쿠키 데이터
   
});

코드 출처, 여기 쿠키 설명 엄청 상세함! 시리즈로 읽어볼 것

Understanding Cookies

https://www.section.io/engineering-education/what-are-cookies-nodejs/
-> 쿠키 역사와 작동 원리에 대해서 적혀 있다.

How cookies work

A perfect example is accessing Facebook from a browser. When you want to access your Facebook account, you have to log in with the correct credentials to be granted the proper access. But in this case, it would be tiresome to continuously log in to Facebook every time.

When you first make a login request and the server verifies your credentials, the server will send your Facebook account content. It will also send cookies to your browser. The cookies are then stored on your computer and submitted to the server with every request you make to that website. A cookie will be saved with an identifier that is unique to that user.

When you revisit Facebook, the request you make, the saved cookie, and the server will keep track of your login session and remember who you are and thus keep you logged in.

프로그래머스 직사각형 별찍기 javascript

process.stdin.setEncoding('utf8');
process.stdin.on('data', data => {
    const n = data.split(" ");
    const a = Number(n[0]), b = Number(n[1]);
//     console.log(a);
//     console.log(b);
    
    
const width = "*".padEnd(a, "*");
const answer = new Array(b).fill(width).join("\n");
console.log(answer);
});

그냥 머리 풀 겸 대충 본 건데 요 문제는 신기하게 백준이랑 비슷한 방식으로 답을 적어야해서 신기했다.
배열로 풀이했다. for문.. 브루탈 포스 유형에서 많이 쓰던데 아직 친숙하지는 않은듯.

process.stdin.setEncoding("utf8");
process.stdin.on("data", (data) => {
  const n = data.split(" ");
  const a = Number(n[0]),
    b = Number(n[1]);

  for (let i = 0; i < b; i++) {
    //i을 선언해주고 몇줄(b)만큼 반복
    let str = ""; //출력할 변수 선언
    for (let j = 0; j < a; j++) {
      // j선언후 별을 한줄에 몇개 찍을지 반복
      str = str + "*"; //출력할 변수에 별을 담는다
    }
    console.log(str); // 출력
  }
});

하루 마무리

  • 완료한 것 ❌ 🔺 ✅
    Express 쿠키를 사용한 로그인 🔺
    자료구조 & 리트코드/프로그래머스 문제 1개 풀기 ✅
    네트워크 (ip계층) 공부 ❌
    SQL 문제 풀기 ✅
  • 내일 쿠키/세션 인증이랑 passport.js 라이브러리 써서 인증인가 구현하는 것 더 봐야겠따. 만약 더 된다면 jwt인증 토큰도 해보고 싶음
  • 하루 반성
    명절 끝났다구.. 의지박약인가... 오전에 집중 못했다. 효율이 높지 못한듯
    cs공부가 점점 뒤로 밀리는게 느껴진다 핳..

  • 피드백
    어 근데 약간 방향성 부스터 다시 단 느낌이라 내일 보고 다시 피드백해봄

0개의 댓글