포스트맨 & REST API

포스트맨 다운로드

웹에서도 가능 

https://www.postman.com/downloads/


HTTP 메서드

HTTP 요청시 클라이언트가 서버쪽에 요청을 원하는 행동 지정

  • GET: 서버로 부터 데이터를 가져오는 요청
  • POST : 데이터를 서버에 보내는 요청
  • PUT : 데이터를 서버에서 수정하는 요청
  • DELETE : 데이터를 서버에서 삭제하는 요청


REST API

WebConfig.java
package com.example.basic.cofigure;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/api/**").allowedOrigins("http://127.0.0.1:5500").allowedMethods("*").allowCredentials(true);
}
}

JoinController.java
package com.example.basic.controller;
import com.example.basic.dto.JoinDTO;
import com.example.basic.entity.JoinEntity;
import com.example.basic.service.JoinService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class JoinController {
private final JoinService joinService;

@PostMapping("/join/create")
public Map<String, Object> create(@RequestBody JoinDTO formDTO ){
String result = joinService.processJoin(formDTO);

Map<String, Object> response = new HashMap<>();
response.put("message", result);
return response;
}

@GetMapping("/admin")
public Object showAdminPage(@RequestParam(defaultValue="0") int page, HttpSession session){
//세션에 유저 정보가 없을 시 에러 객체 반환
// if(session.getAttribute("loginUer") == null){
// // Map.of(key, value); 간단한 구조의 객체 생성 (수정 불가)
// return Map.of("error", "로그인이 필요합니다.");
// }

int pageSize = 3;
Page<JoinEntity> userPage = joinService.getUsersByPage(page, pageSize);

Map<String, Object> result = new HashMap<>();
result.put("users", userPage.getContent());
result.put("currentPage", page);
result.put("totalPages", userPage.getTotalPages());
return result;
}

@DeleteMapping("/admin/del/{id}")
public Map<String, String> delUser(@PathVariable Long id){
joinService.delete(id);
Map<String, String> result = new HashMap<>();
result.put("message", "삭제 성공");
return result;
}
}

index.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css/style.css">
  <script defer src="user.js"></script>
  <title>Document</title>
</head>

<body>
  <header>
    <h1><a href="index.html">Logo</a></h1>

    <nav>
      <a href="join.html">Join</a>
    </nav>
  </header>
  <section></section>
</body>

</html>


user.js
getUsers(1);

// DB에서 회원 정보 호출 및 동적 리스트 생성 함수
async function getUsers(pageNum = 0) {
  const section = document.querySelector("section");
  const res = await fetch(`http://localhost:8080/api/admin?page=${pageNum}`);
  const data = await res.json();
  const userArr = data.users;
  console.log(userArr);
  let tags = "";

  userArr.forEach((user) => {
    tags += `
      <article>
        <h2>${user.uname}</h2>
        <p>${user.email}</p>
        <span>${user.colors}</span>
        <button class='btnDel' data-id=${user.id}>delete</button>
      </article>
    `;
  }); //tags 반복 끝

  section.innerHTML = tags;

  const btns = document.querySelectorAll(".btnDel");

  btns.forEach((btn) => {
    btn.addEventListener("click", async (e) => {
      const memberId = e.currentTarget.getAttribute("data-id");
      console.log(memberId);

      const data = await fetch(
        `http://127.0.0.1:8080/api/admin/del/${memberId}`,
        {
          method: "DELETE",
        }
      );
      result = await data.json();
      alert(result.message);
      location.href = "index.html";
    });
  });
}


join.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script defer src="form.js"></script>
</head>

<body>
  <header>
    <h1><a href="index.html">Logo</a></h1>

    <nav>
      <a href="join.html">Join</a>
    </nav>
  </header>

  <main>
    <form id="join">
      <label>Name</label> <input type="text" name="uname" id="uname" /><br />
      <label>Email</label> <input type="email" name="email" id="email" /><br />

      <h3>Favorait Color</h3>
      <label>red</label><input type="radio" name="colors" value="red">
      <label>green</label><input type="radio" name="colors" value="green">
      <label>blue</label><input type="radio" name="colors" value="blue">

      <button type="submit">Send</button>
    </form>
  </main>
</body>

</html>


form.js
//회원정보 DB 저장 함수

document.querySelector("#join").addEventListener("submit", (e) => {
  e.preventDefault();
  sendForm();
});

async function sendForm() {
  const uname = document.querySelector("input[name='uname']");
  const email = document.querySelector("input[name='email']");
  const colors = document.querySelector("input[name='colors']:checked");

  const userInfo = {
    uname: uname.value,
    email: email.value,
    colors: colors.value,
  };

  const strJson = JSON.stringify(userInfo);
  const data = await fetch("http://127.0.0.1:8080/api/join/create", {
    headers: {
      "Content-Type": "application/json",
    },
    method: "POST",
    body: strJson,
  });

  const result = await data.json();
  alert(result.message);
  location.href = "index.html";
}






댓글 쓰기

다음 이전