TIL_21.02.23(화)~26(금)

nRecode·2021년 2월 23일
0

TodayILearned

목록 보기
89/95
post-thumbnail

02.23(화)

express, Event Loop 전에 작성한 TIL참고하여 express 프레임 위크로 변경을 위한 express 공부

express는 미들웨어를 붙이기 쉽고 자체 라우터를 제공한다는 장점이 있다.

미들웨어가 주로 쓰이는 상황

  1. 모든 요청에 대해 url이나 메소드를 알고자 할 때
  2. POST요청에서 body(payload)를 쉽게 얻고자 할 때
  3. 모든 요청/응답에 CORS 헤더를 붙일 때
  4. 요청헤더에 사용자 인증정보가 담겨있는지 확인하고 싶을 때

http vs express

case 2 : POST요청에서 body(payload)를 쉽게 얻고자 할 때

http

let body = [];
request.on('data', (chunk) => {
  body.push(chunk);
}).on('end', () => {
  body = Buffer.concat(body).toString();
  // body 변수에는 문자열 형태로 payload가 담겨져 있습니다.
});

express

const bodyParser = require('body-parser')
const jsonParser = bodyParser.json()

// 생략
app.post('/api/users', jsonParser, function (req, res) {
  // req.body에는 JSON의 형태로 payload가 담겨져 있습니다.
})

case 3 : 모든 요청/응답에 CORS 헤더를 붙일 때

http

const defaultCorsHeader = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Accept',
  'Access-Control-Max-Age': 10
};

// 생략
if (req.method === 'OPTIONS') {
  res.writeHead(201, defaultCorsHeader);
  res.end()
}

express

const cors = require('cors')

// 생략
app.use(cors()) // 모든 요청에 대해 CORS 허용

case 4:요청헤더에 사용자 인증정보가 담겨있는지 확인하고 싶을 때

토큰의 여부를 판단하고 로그인한 사용자가 아닐 경우 에러를 보내는 미들웨어

app.use((req, res, next) => {
  // 토큰 있니? 없으면 받아줄 수 없어!
  if(req.headers.token){
    req.isLoggedIn = true;
    next()
  } else {
    res.status(400).send('invalid user')
  }
})

02.24(수)

express로 변경

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

const PORT = 3001;

const bodyParser = require('body-parser');
const cors = require('cors');


const results = {results: []};

// next는 다음 컨베이어 벨트로 넘기는 역할을 하는 것 
// next 없애니까 get 메소드 진행 안됐음
var myLogger = function (req, res, next){
    console.log(`http request method is ${req.method}, url ${req.url}`);
    next();
}

app.use(myLogger);

app.use(bodyParser.json());
app.use(cors());

app.get('/',function(req, res){
    res.send('Hello World');
});

app.get('/classes/messages',function (req, res){
    res.status(200).send(results);
});

app.post('/classes/messages', function(req, res){
    const {body} = req;
    results.results.push(body);
    res.status(201).send(body);
});

app.listen(PORT, () => {
    console.log(`server listen on ${PORT}`)
});

02.26(금)

TIL_20.06.11(목) - SQL

SQL

데이터베이스용 프로그래밍 언어
Structured Query Language -> 구조화 된 쿼리 언어
쿼리는 직역하자면 질의문. 저장되어 있는 정보를 필터하기 위한 질문

DB가 필요한 이유

In memory - 서버를 끄면 데이터가 사라짐
File I/O - 원하는 데이터만 가져올 수 없고 모든 데이터를 필터링을 필요로 한다.
DataBase - 필터링 외에도 File I/O로 구현이 힘든 관리를 위한 여러 기능들을 가지고 있는 데이터에 특화된 서버

w3schools 실습

w3schools | Quiz
w3schools | Practice


SELECT 열명 FROM 테이블명;(DISTINCT는 중복제거)
ex) Select all the different values from the Country column in the Customers table.

SELECT DISTINCT Country FROM Customers;

NOT키워드(AND, OR 가능)
ex) Use the NOT keyword to select all records where City is NOT "Berlin".

SELECT * FROM Customers WHERE NOT City = "Berlin";

INSERT INTO 테이블명(삽입할 열들) VALUES(삽입할 데이터들)
ex) Insert a new record in the Customers table.

INSERT INTO Customers (CustomerName, Address, City, PostalCode, Country) 
VALUES ('Hekkan Burger', 'Gateveien 15', 'Sandnes', '4306', 'Norway');

UPDATE 테이블명 SET 변경할 데이터가 있는 열 = 변경할 값;
ex) Update the City value and the Country value.

UPDATE Customers SET City = 'Oslo', Country = 'Norway'
WHERE CustomerID = 32;

DELETE FROM 테이블 명;
ex) Delete all the records from the Customers table where the Country value is 'Norway'.

DELETE FROM Customers WHERE Country = 'Norway';

SELECT MIN(값을 구할 열) FROM 테이블명;
ex) Use the MIN function to select the record with the smallest value of the Price column.

SELECT MIN(Price) FROM Products;

SELECT COUNT(column_name) FROM table_name
WHERE condition;

ex) Use the correct function to return the number of records that have the Price value set to 18.

SELECT COUNT (*) FROM Products WHERE Price = 18; 

SELECT AVG/SUM(column_name) FROM table_name

SELECT SUM(Price) FROM Products;

LIKE(wildcard를 곁들인...)
w3schools | LIKE
ex) Select all records where the value of the City column does NOT start with the letter "a".

SELECT * FROM Customers WHERE City NOT LIKE "a%"
;

IN(여러 or의 약어)
ex) Use the IN operator to select all the records where Country is either "Norway" or "France".

SELECT * FROM Customers WHERE Country IN ('Norway', 'France');

JOIN ON
w3school | JOIN
ex) Choose the correct JOIN clause to select all records from the two tables where there is a match in both tables.

SELECT * FROM Orders JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

ORDER BY
ex) List the number of customers in each country, ordered by the country with the most customers first.

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
profile
안정성, 확장성 있는 서버를 구축하고 가꾸는 개발자를 목표로 공부하고 있습니다. 🤔🤔🤔🤔 부족하기에 맞지 않는 내용이 있을 수 있습니다. 가감없이 피드백 해주시면 정말 감사하겠습니다..🙏

0개의 댓글