type Score = 'A' | 'B' | 'C' | 'D' ;

interface User {
  name : string;
  age : number;
  gender? : string;
  readonly birthYear : number;
  [ grade:number ] : Score; 
}

let user: User= {
  name: 'aaa',
  age : 30,
  gender : 'female',
  birthYear : 1990,
  1 : 'A',
  2 : 'C'
};

user.gender = "male"
user.birthYear = 1987; //(error) readonly 여서 변경 불가

 

Interface 로 함수 정의 

interface Add{
  (num1:number, number2:number):number;
}

const add :Add = function(x, y){
  return x + y;
}

add(10, '20') // number가 아니여서 에러
add(10,20) //30

interface IsAudlt {
  (age: number):boolean;
}

const a: IsAudlt = function(x){
  return x > 19 ;
}

a(30) // true​

 

Interface 로 클래스 정의 및 확장

//Implements && extend

interface Car{
  color: string;
  wheels: number;
  start(): void;
}

interface Benz extends Car {
  door : number;
  stop() :void;
}

class Bmw implements Car{
  color;
  wheels = 4;
  constructor(c: string){
    this.color = c;
  }
  start(){
    console.log('go..')
  }
}

const b = new Bmw('blue');
b.start()

const benz :Benz = {
  door: 5,
  stop(){
    console.log('stop...');
  },
  color: 'green',
  wheels: 4,
  start(){
    console.log('go..')
  }
}

 

여러 Interface 로 확장

interface Car{
  color: string;
  wheels: number;
  start(): void;
}
interface Toy{
  name: string;
}

interface ToyCar extends Car, Toy {
  price: number;
}

 

 

참고한 강좌 : https://www.youtube.com/watch?v=prfgfj03_VA&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=3 

'프로그래밍 > TypeScript' 카테고리의 다른 글

[TS] 유니온 Union Types  (0) 2024.03.06
[TS] 리터럴 타입 (Literal Types)  (0) 2024.03.06
[TS] 함수 - bind 및 오버로드 이용  (0) 2024.03.06
[TS] 함수  (0) 2024.03.06
[TS] 타입스크립트를 사용하는 이유  (0) 2024.03.05

코드를 작성하고 실행을 하면서 에러를 발견하게 되는 경우가 두가지가 있다.

1. 런타임 에러 : 코드를 실행 후 알 수 있는 에러

2. 컴파일 에러 : 코드를 작성 중에 생기는 에러

 

이 두가지 중 선호되는 방식은 컴파일 에러다.

JavaScript 는 동적인 언어. 즉, 변수의 타입이 정해져 있지 않다-> 런타임 에러

TypeScript 는 정적인 언어. 즉, 변수의 타입이 정해져 있다. -> 컴파일 에러

 

→ 시간은 많이 걸리더라도 안정적으로 코드를 작성하기 위해서 TypeScript를 사용한다.

'프로그래밍 > TypeScript' 카테고리의 다른 글

[TS] 유니온 Union Types  (0) 2024.03.06
[TS] 리터럴 타입 (Literal Types)  (0) 2024.03.06
[TS] 함수 - bind 및 오버로드 이용  (0) 2024.03.06
[TS] 함수  (0) 2024.03.06
[TS] 인터페이스(interface) 사용방법  (0) 2024.03.05

Path Params : 리소스를 식별

Query String : 요청의 성격을 명확히 ( 정렬, 필터링, ...)

Request Body  : 복잡한 데이터를 전송

Path Params (경로 매개변수)

  • 목적: 리소스 식별
    • 리소스 식별: 경로 매개변수는 주로 리소스나 리소스의 특정 부분을 식별하는 데 사용됩니다. 예를 들어, /users/123 에서  123 은 사용자 리소스의 고유 ID를 나타내는 경로 매개변수입니다.
  • 특징:
    • 필수 정보: URL의 구조적인 부분으로, 해당 리소스에 접근하기 위해 필수적인 정보를 포함합니다.
    • 계층적 데이터: 계층적인 데이터 구조를 나타내기에 적합하며, URL의 경로 부분에 자연스럽게 매핑됩니다.
      • /countries/korea/cities/seoul -> 국가와 도시를 계층적으로 표현
  • 적합한 상황:
    API URL이 리소스의 고유한 위치를 나타내야 할 때, 즉 URL의 구조가 리소스의 식별에 직접적으로 사용되는 경우에 적합합니다.
  • 사용 예:
    • 특정 사용자의 프로필 페이지에 접근할 때 (/users/123)
    • 특정 게시글을 조회할 때 (/posts/456)

Query String (쿼리 스트링)

  • 목적: 필터링, 정렬, 검색
  • 특징:
    • 선택적 정보: 선택적인 요청 데이터를 전달하는 데 사용되며, 이 데이터 없이도 기본적인 요청 처리가 가능합니다.
    • 비계층적 데이터: 비계층적 데이터를 전달하는 데 적합하며, 다양한 종류의 데이터를 유연하게 전달할 수 있습니다.
  • 적합한 상황:
    요청이 리소스에 대한 비계층적 데이터를 필터링하거나, 정렬, 검색 조건을 지정하는 등의 추가적인 정보를 제공해야 할 때 적합합니다.
  • 사용 예:
    • 특정 조건에 맞는 상품 목록을 조회할 때 (/products?type=electronics&price_range=100-500)
    • 검색 결과를 특정 방식으로 정렬하거나 페이징 처리할 때 (/search?q=keyword&page=2&sort=date)

Request Body (요청 본문)

  • 목적: 복잡한 데이터 전송
  • 특징:
    • 복잡한 데이터 구조: JSON, XML 등의 형식을 사용하여 복잡한 구조의 데이터를 전송하는 데 적합합니다.
    • 데이터의 양: 대량의 데이터를 전송할 수 있으며, 특히 POST, PUT, PATCH 요청에서 리소스 생성, 업데이트, 수정에 사용됩니다.
  • 적합한 상황:
    POST, PUT, PATCH 같은 메소드를 사용하여 리소스를 생성, 업데이트 또는 수정할 때 사용됩니다. 예를 들어, 새로운 사용자를 생성하는 POST 요청에서 요청 본문은 사용자의 이름, 이메일 등을 포함할 수 있습니다.
  • 사용 예:
    • 새로운 사용자 등록, 사용자 정보 업데이트 (POST /users, PUT /users/123)
    • 게시글 작성, 댓글 달기 등의 작업에서 복잡한 내용을 전송할 때

요약

  • Path Params는 URL의 일부로서 리소스를 직접적으로 식별하는 정보를 포함합니다. 주로 리소스의 위치나 고유한 식별자를 나타내는 데 사용됩니다.
  • Query String은 URL에 추가적인 정보를 제공하는 선택적 매개변수를 포함하여, 리소스에 대한 추가 조건이나 요구 사항을 전달하는 데 사용됩니다. 이는 주로 필터링, 검색, 정렬 등의 작업에 적합합니다.
  • Request Body는 주로 HTTP 메소드가 POST, PUT, PATCH인 경우에 사용되며, 리소스의 생성, 업데이트, 수정과 같은 작업에 필요한 복잡한 데이터나 대량의 정보를 전송하는 데 사용됩니다.

각각의 방법은 API의 목적, 리소스의 구조, 요청의 성격을 기반으로 적절하게 선택되어야 합니다. 따라서, API를 설계할 때는 이러한 요소들을 고려하여 가장 효율적이고 명확한 데이터 전송 방법을 결정해야 합니다.

Node.js + express.js 사용

  • 설치 
npm i cors
  • 코드 예시

>  모든 요청 허용

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

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This allow all CORS request'})
})

// 나머지 서버 코드...

 

>  특정 도메인 허용

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

const corsOptions = {
    origin: 'http://example.com', // 특정 도메인 허용, 리스트로 작성 가능
    methods: 'GET,POST,PUT,DELETE', // 허용하는 HTTP 메소드
    credentials: true // 쿠키/인증 정보 허용
}

app.use(cors(corsOptions));

app.get('/products/:id', (req, res) =>{
	// 나머지 코드...
})

// 나머지 코드...

 

아래 참고자료 링크에서 더 많은 예제 및 옵션 참고 가능

참고자료

https://www.npmjs.com/package/cors

*Origin: scheme(protocol), hostname(domain), port of URL

 

HTTP-header 기반의 보안 메커니즘

즉, web brower에서 실행 되는 보안 조치

 

탄생배경

  • 도메인간의 요청이 오고가면서 보안의 위험이 발생
  • SOP(the same-origin policy)의 한계 발생
    • SOP:  한 도메인의 문서나 스크립트가 어떻게 다른 도메인과 상호작용을 할건지에 대한 보안 메커니즘
    • 한계점
      • 다른 도메인들에 있는 API들간의 데이터 공유시 보안 문제
      • 웹 app 에서 다루는 다양한 소스로 부터 얻은 데이터 처리
      • 최근 웹 어플리케이션에서 발생 하는 다양한 리소스및 서비스간 의  cross-origin interaction을 다루지 못함
        • 다른 도메인에서 리소스 로드
        • 외부서비스에 API call 생성 ( 한 app 에서 다른 서버에 있는 API에 요청을 하는 행위)

목적

  • SOP 를 기반으로 유연하고 안전하게 cross-origin requests 를 하기 위함
  • 유저의 데이터 보호
  • 악의적인 웹페이지가 다른 도메인의 민감한 정보에 대한 접근을 방지

 

동작방식

  1. 웹 페이지 A가 특정 서버에 데이터를 요청
  2. 원하는 것이 무엇인지에 대한 정보가 있는 `Origin`을 헤더에 담아서 요청 전송
  3. 해당 서버는 CORS 정책에 따라 이 요청을 허락할지 거절할지 결정
  4. 요청을 허락하게 되면 CROS 는 `Access-Control-Allow-Origin` 라는 헤더에 허락된 origin 정보를 담아서 응답
    • 이 헤더에는 허락된 origin을 담거나, 모든 origin을 허용하는 와일드 카드인 `*` 를 사용할 수 있다. 

 

참고자료

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

https://www.npmjs.com/package/cors

https://chat.openai.com/c/67d26a77-236d-4937-968a-412b96379988

ChatGPT 답변 + 내용 수정

더보기

Certainly! CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented in web browsers to manage how web applications running at one origin (domain) can request resources from another origin.

Here's a breakdown of its key aspects:

  1. Same-Origin Policy: By default, web browsers enforce a security measure called the Same-Origin Policy (SOP). This policy restricts web pages from making requests to a different domain than the one that served the web page. Its primary purpose is to protect user data and prevent malicious scripts on one page from obtaining access to sensitive data on another.
  2. The Need for CORS: Sometimes, legitimate web applications need to make cross-origin requests. For example, a web application hosted on example.com might need to request resources from api.example.com or a third-party API hosted on a different domain. CORS provides a way to allow these cross-origin requests safely.
  3. How CORS Works: CORS works through HTTP headers.
    • When a web application makes a cross-origin request, the browser sends an HTTP request to the target server with an `Origin` header, indicating the origin of the request.
    • The server can then decide whether to allow or deny the request based on its CORS policy. If the server allows the request, it responds with specific CORS headers, like `Access-Control-Allow-Origin`, indicating which origins are permitted.
    • This header lists the allowed origns or a wildcard to indicagte that any origins is allowed.
  4. Simple and Preflight Requests: There are two types of CORS requests - Simple and Preflight. Simple requests are basic requests like GET or POST with certain safe headers, and they are sent directly with CORS headers. Preflight requests are more complex and use methods like PUT or DELETE, or include custom headers. These are first sent with an OPTIONS request to check if the actual request is safe to send.
  5. Security and Limitations: While CORS enables cross-origin requests, it also includes mechanisms to ensure security. It doesn't allow arbitrary sharing of user credentials like cookies or HTTP authentication unless explicitly permitted by the server. Also, CORS policies are set server-side, meaning the server has full control over who can access its resources.

In summary, CORS is an essential part of modern web security. It enables controlled cross-origin requests, balancing the need for functionality with the need to protect users' data and privacy.

 

Simple Example

 

Imagine you have two websites:

  1. Website A: https://website-a.com, which is a frontend application.
  2. Website B: https://api.website-b.com, which provides an API that Website A wants to use.

Scenario Without CORS

  • A user visits https://website-a.com.
  • Website A tries to fetch user data from https://api.website-b.com/data.
  • The browser's Same-Origin Policy blocks this request because it's a cross-origin request (the origin of the frontend app is website-a.com, and it's trying to access data from api.website-b.com).

Implementing CORS

To allow this cross-origin request, Website B (the API server) needs to include a specific header in its response.

Steps in the CORS Process

  1. The Browser Sends a Request: When the frontend app at Website A makes a request to Website B, the browser automatically adds an Origin header to the request, indicating that the request is coming from https://website-a.com.
  2. Server Checks the Origin: Website B's server receives the request and checks the Origin header.
  3. Server Responds with CORS Headers: If Website B's server is configured to allow requests from https://website-a.com, it responds with a header like Access-Control-Allow-Origin: https://website-a.com. This header tells the browser that the cross-origin request is permitted.
  4. Browser Processes the Response: The browser sees the Access-Control-Allow-Origin header in the response and allows the frontend JavaScript code on Website A to access the response data.

Code Example

Here's what the HTTP headers might look like:

Request from Website A to Website B

GET /data HTTP/1.1
Host: api.website-b.com
Origin: https://websites-a.com

Request from Website A to Website A

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://website-a.com
Content-Type: application/json

{
	"data" : "sample data"
}

Conclusion

In this example, CORS enables Website A to safely and successfully request data from Website B, despite being on different origins. Without CORS, this kind of cross-origin request would be automatically blocked by the browser for security reasons.

 

 

 

+ Recent posts