Web

RESTful 라우트

taenyLog 2023. 6. 24. 06:27
반응형

Get 요청 / Post 요청

Get

- 요청정보를 가져옴

- get 요청을 보낼 때 따라오는 데이터는 쿼리 문자열에 담김(URL에서 볼 수 있다.)

- 백엔드까지 영향을 주진않는다.

 

Post

- 정보를 보내거나 올림

- body에 포함

- Json 타입으로 보낼 수 있음

- 생성/ 삭제 / 업데이트

 

 

Express Post 경로 정의

Get과 Post를 구별해서 받음

 

요청 구문 분석하기

다른 포맷으로 데이터를 보낼 수 있다

http://expressjs.com/en/5x/api.html#req.body

 

Express 5.x - API Reference

Express 5.x API Note: This is early beta documentation that may be incomplete and is still under development. express() Creates an Express application. The express() function is a top-level function exported by the express module. const express = require('

expressjs.com

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

 

As req.body’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

 

The following example shows how to use body-parsing middleware to populate req.body.

const app = require('express')()
const bodyParser = require('body-parser')
const multer = require('multer') // v1.0.5
const upload = multer() // for parsing multipart/form-data

app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.post('/profile', upload.array(), (req, res, next) => {
  console.log(req.body)
  res.json(req.body)
})

 

 

 

REST 개요

REST : REPRESENTATIONAL STATE TRANSFER 

 분산 하이퍼미디어 시스템의 아키텍처 스타일/패러다임

클라이언트와 서버가 어떻게 소통해야하는지 가이드라인

resource = entity 

HTTP를 통해 접근을 노출하거나 제공하는 엔티티

 

https://ko.wikipedia.org/wiki/REST

 

REST - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. 대한민국의 힙합 음악가에 대해서는 R-EST 문서를 참고하십시오. 다른 뜻에 대해서는 레스트 문서를 참고하십시오. REST(Representational State Transfer)는 월드 와이드

ko.wikipedia.org

 

 

 

RESTful 주석 개요

RESTful 서버 아키텍처 구현

CRUD 청사진. 
GET /comments - list all comments
POST /comments - Create a new comment
GET /comments/:id - Get one comment(using ID)
PATCH /comments/:id - Update one comment
DELETE /comments/:id - Destroy one comment

 

 

Express 방향 수정

실제로는 post 라우트에서 직접 렌더링하지않고 사용자를 redirect 한다. 

https://expressjs.com/en/api.html

 

Express 4.x - API Reference

Express 4.x API express() Creates an Express application. The express() function is a top-level function exported by the express module. var express = require('express') var app = express() Methods express.json([options]) This middleware is available in Ex

expressjs.com

res.redirect([status,] path)

Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.

res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')

Redirects can be a fully-qualified URL for redirecting to a different site:

res.redirect('http://google.com')

Redirects can be relative to the root of the host name. For example, if the application is on http://example.com/admin/post/new, the following would redirect to the URL http://example.com/admin:

res.redirect('/admin')

Redirects can be relative to the current URL. For example, from http://example.com/blog/admin/ (notice the trailing slash), the following would redirect to the URL http://example.com/blog/admin/post/new.

res.redirect('post/new')

Redirecting to post/new from http://example.com/blog/admin (no trailing slash), will redirect to http://example.com/blog/post/new.

If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.

Path-relative redirects are also possible. If you were on http://example.com/admin/post/new, the following would redirect to http://example.com/admin/post:

res.redirect('..')

A back redirection redirects the request back to the referer, defaulting to / when the referer is missing.

res.redirect('back')

 

post 라우트에서 사용자를 redirect 하는 방법

app.post("/comments", (req, res) => {
  const { username, comment } = req.body;
  comments.push({ username, comment });
  res.redirect('/comments');
  // 생성된 응답에는 리디렉션 상태코드(기본 : 302) 포함
  // 브라우저가 /comments 사용해 새로 요청함. 
});

 

RESTful 주석 Show

데이터의 id 값을 받아서 클릭시 해당 글의 내용을 찾아가도록 설계

app.get("/comments/:id",(req,res)=>{
    const {id} = req.params; //req.params은 문자열이 될것이다. 따라서 parseInt(id)로 숫자로 만들어줌
    // 배열 메서드 find 써서 comments.find에 콜백 전달함 
    const comment = comments.find(c=>c.id === parseInt(id));
    res.render('comments/show',{comment})
})

detail 클릭시 해당 글의 내용 보여줌. 

 

 

UUID 패키지

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

 

uuid

RFC4122 (v1, v4, and v5) UUIDs. Latest version: 9.0.0, last published: 10 months ago. Start using uuid in your project by running `npm i uuid`. There are 54515 other projects in the npm registry using uuid.

www.npmjs.com

홈(index) 로 돌아갈때 리셋되지않고 데이터를 가지고 돌아가도록 설계

(데이터베이스 DB 흉내내기)

 

index.js

const { v4: uuid } = require('uuid');
const comments = [
  {
    id : uuid(),
    username: "Todd",
    comment: "lol ",
  },
  {
    id : uuid(),
    username: "ZEDD",
    comment: "how cool  ",
  }]
app.post("/comments", (req, res) => {
  const { username, comment } = req.body;
  comments.push({ username, comment , id:uuid()}); // id가 uuid()를 호출한 새로운 결과가 되도록 설정
  res.redirect('/comments');
});
app.get("/comments/:id",(req,res)=>{
    const {id} = req.params; 
    const comment = comments.find(c => c.id === id); 
    //find는 처음으로 일치하는 요소만준다 : 즉 첫번째 댓글
    res.render('comments/show',{comment})
})

 

 

RESTful 주석 Update

Update로 다루는 건 Put과 Patch이다.

 

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

 

HTTP request methods - HTTP | MDN

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred to as HTTP verbs. Each of them implements a different semantic, but som

developer.mozilla.org

PATCH : Applys partial modifications to a resource

PUT : Replaces all current representations of the target resource with the request payload

 

PUT은 전체내용 업데이트

PATCH 요청은 기존 리소스에 업데이트하거나 추가 할 때 사용 (사용자 이름인 id는 놔두고 글내용만 수정)

app.patch('/comments/:id',(req,res)=>{
    const {id} = req.params; // url에서 req.params인 ID를 가져온 후
    const newCommentText = req.body.comment; // req.body.comment에 담긴 페이로드를 가져옴
    const foundComment = comments.find(c => c.id === id);  // 해당 id로 글을 찾는다
    foundComment.comment = newCommentText; // 업데이트함
    res.redirect('/comments');
})

글 업데이트하는 방식이 요즘의 웹개발에서는 권장하지 않는 방식이다.

배열에 있는 객체를 변형한 것이다 . 요즘은 객체를 변형하지 않는 불변성 강조함

 

 

Express 메서드 재정의

http://expressjs.com/en/resources/middleware/method-override.html

 

Express method-override middleware

method-override Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn’t support it. Install This is a Node.js module available through the npm registry. Installation is done using the npm install command: $ npm install method-ove

expressjs.com

브라우저의 폼에서는 포스팅에 get말고는 다 불가능하다. 

method-override 는 브라우저 폼처럼 클라이언트가 해당작업을 지원하지 않는 환경에서

Put, Delete등의 HTTP동사를 쓰도록 해줌

 

<body>
    <h1>EDIT</h1>
<form method="post" action="/comments/<%= comment.id%>?_method=PATCH">
    <!-- post를 전송하는거지만 express를 속여서 Patch요청이라고 생각하게 만듦 -->
    <textarea name="comment" id="" cols="30" rows="10">
        <%= comment.comment  %>
    </textarea>
    <button>SAVE</button>
</form>
</body>
const methodOverride = require('method-override')
app.use(methodOverride('_method'))

 

 

RESTful 주석 Delete

브라우저에서 HTML 폼을 이용해 Patch나 Delete 요청을 보낼 수 없다 

Axios를 사용해 요청을 보내거나 JavaScript나 Fetch등으로 요청 보낼 수 있다.

폼요소로는 보낼수 없음 !! 흉내만 가능 

    <form method="POST" action="/comments/<%= comment.id %>?_method=DELETE">
      <button>Delete</button>
    </form>
app.delete('/comments/:id',(req,res)=>{
    const {id} = req.params; 
    // id를 찾은 후 comments.filter()로 라우트에 있는 ID와 동일하지 않는 댓글의 id 찾음
    comments = comments.filter(c => c.id !== id) ;
    res.redirect('/comments')
})

 

 

반응형