Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

NodeJS - RESTful, URL, URI, Request method (GET, POST) 본문

NodeJS

NodeJS - RESTful, URL, URI, Request method (GET, POST)

보람- 2023. 9. 11. 17:59

 


목차

1. URL과 URI

2. Requset Method (GET, POST)

3. redirect()

4. bodyString


 

 

 

 

1. URL과 URI

- nodejs공식문서에서  URL 을 검색하면 URL 문자열은 여러 의미 있는 구성 요소를 포함하는 구조화된 문자열이고, 구문 분석 시 이러한 각 구성 요소에 대한 속성이 포함된 URL 객체가 반환된다고 한다.

 

URL →  https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash 

host →  sub.example.com:8080

 

라이브서버를 열었을때 http://127.0.0.1:5500/index.html 로 열리는데, 파일네임과 확장자까지 뜨게된다.

 

URL : http://127.0.0.1:5500/index.html

URI : http://127.0.0.1:5500/index

 

 

 

 

2. Requset Method (GET, POST)

  <body>
    <h2>글쓰기 페이지 입니다.</h2>

    <form method="post" action="/board/write">
      <ul>
        <li>작성자 : <input type="text" name="writer2" id="writer1" /></li>
        <li>제목 : <input type="text" name="subject2" id="subject1" /></li>
        <li>
          <textarea name="content2" id="content1"></textarea>
        </li>
      </ul>
      <button type="submit">글쓰기</button>
    </form>
  </body>

- form을 사용해서 method, action을 입력해준다.

 

parseURI(path) {
    // path = '/board/list?name=boram&id=guniee'
    const [pathname, queryString] = path.split("?");
    return [pathname, queryString];
  }
parseQueryString(queryString) {
    if (!queryString) return null;
    const query = queryString
      .split("&")
      .map((valule) => valule.split("="))
      .reduce((acc, line) => {
        const [key, valule] = line;
        acc[key] = valule;
        return acc;
      }, {});
    return query;
  }

- request 파일에서 uri메서드를 만들어주고, 리턴값으로 나온 []을 풀어서 {} 객체로 만들어주기

  → 서버측에서 url에 ? 를 기준으로 뒤에를 uri로 인식하도록!

        

 

 

 

3. redirect()

// response.js 파일에서

const STATUS_MESSAGE = {
  200: "OK",
  404: "NOT FOUND",
  302: "FOUND"
};

 redirect(pathname) {
    this.setStatus(302);
    this.setHeaders("Location", pathname);
    this.end();
  }
// server.js 파일에서

if (req.headers.method === "GET" && req.headers.uri === "/boards/list") {
  res.sendFile("list.html");
} else if (
  req.headers.method === "GET" &&
  req.headers.uri === "/boards/write"
) {
  res.sendFile("write.html");
} else if (
  req.headers.method === "POST" &&
  req.headers.uri === "/boards/write"
) {
  console.log(req.headers["Content-Type"]);
  console.log(req.body); // writer2=asdfasdf&subject2=asdfasdfasdf&content1=asdfasdfasdf
  res.redirect("/boards/list")
}

 

 

 

 

4. bodyString

// request.js 파일에서


body = null;

constructor(buffer) {
    const [headerString, bodyString] = this.getRequestMessage(buffer);
    this.setRawHeader(headerString);

    const startLine = this.parseStartLine();
    this.headers = { ...startLine };

    const headers = this.parseHeaders();
    this.headers = { ...this.headers, ...headers };

    this.body = this.parseQueryString(bodyString);
    
  }

parseStartLine() {
    const startLine = this.rawStartLine.split(SPACE);
    const mappingName = startLine.map((valule, index) => [
      START_LINE_NAMES[index],
      valule,
    ]);
    const obj = mappingName.reduce((acc, line) => {
      const [key, valule] = line;
      acc[key] = valule;
      return acc;
    }, {});

    const [pathname, queryString] = this.parseURI(obj.uri);
    obj.uri = pathname;

    const query = this.parseQueryString(queryString);
    obj.query = query;
    return obj;
  }

- bodyString 작업마저 해주고나면 input에 적은 내용이 {} 안에 담겨진다.

  → { writer2: 'dfd', subject2: 'dfd', content2: 'dfd' }

- POST를 넣었다면, 페이로드에서 쿼리스트링 정보가 보여진다.

 

 

- express와 비교하자면 아래 2개는 parse를 해주는 코드인것이다!

app.use(express.json())
app.use(express.urlencoded({extended:true}))

- 헤더속 Content-Type 이 어떤것인지를 알려주는것!

  → POST로 html일 경우 application/x-www-form-urlencoded (디폴트)

  → JSON일경우 application/json

 

 

 

 


※ NodeJS 공식문서 - URL 참고

https://nodejs.org/dist/latest-v18.x/docs/api/url.html

 

URL | Node.js v18.17.1 Documentation

URL# Source Code: lib/url.js The node:url module provides utilities for URL resolution and parsing. It can be accessed using: import url from 'node:url';const url = require('node:url');copy URL strings and URL objects# A URL string is a structured string c

nodejs.org

※ restful 간단정리 참고

https://hahahoho5915.tistory.com/54