자바스크립트

[Vanilla JS] fetch - POST, application/x-www-form-urlencoded 로 요청하기!

h__hj 2022. 9. 4. 20:07

# fetch - POST, application/x-www-form-urlencoded

 주로 사용하는 ajax 대신 fetch 로 POST방식 application/x-www-form-urlencoded 타입으로 통신하기!

# 환경

/**
 * tool: sts 4.13.0
 * version: 2.7.3-SNAPSHOT
 * java: 1.8
 * type: maven
 * view: Thymeleaf
 */

# test page

# test page html

<h1>바닐라JS 테스트 페이지 입니다.(not use jQuery)</h1>

<h3>fetch</h3>
<input type="text" id="reqValue" value="테스트" style="display: inline;"/>
<input type="button" onclick="get()" value="GET" style="display: inline;"/>
<input type="button" onclick="post()" value="POST" style="display: inline;"/>
<input type="button" onclick="json()" value="JSON" style="display: inline;"/>

# fetch (post) javascript example code

function post() {
    const params = {
        text: reqValue.value,
        number: 1002
    }
    fetchPost("/test/vanilla/fetch/post", params)
        .then((data) => console.log('OUTPUT:', data.type, data.result))
        .catch((error) => console.log(error))
    ;
}
// FORM POST 메서드 구현 예제
async function fetchPost(uri, params) {
    const data = new URLSearchParams(params);
    console.log('INPUT:', data);
		
    const header = document.querySelector("meta[name='_csrf_header']").attributes.content.value;
    const token  = document.querySelector("meta[name='_csrf']").attributes.content.value;
		
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    headers.append(header, token);
        
    const response = await fetch(uri, {
        method: 'POST',
        headers: headers,
        body: data,
    });
		
    return response.json();
}
  • header, token은 제외해도 됨.
  • Security Config + csrf 활성화 상태라서 작성한 코드.

# fetch (post) java example code

@Slf4j
@Controller
@RequestMapping("/test/vanilla")
public class TestVanillaController {

    @PostMapping("/fetch/post")
    public ModelAndView fetchPost(@RequestParam Map<String, Object> input) {
        log.debug("[PARAMETER] {}", input);
        ModelAndView mav = new ModelAndView("jsonView");
		
        mav.addObject("result", input);
        mav.addObject("type", "post-form");
        return mav;
    }
}

# log

javascript log
INPUT: URLSearchParams {}[[Prototype]]: URLSearchParams
OUTPUT: post-form {text: '테스트', number: '1002'}

java log
[PARAMETER] {text=테스트, number=1002}
  • URLSearchParams 은 data.get('text'), data.get('number')로 값 확인 가능.

# Vanilla JS 시리즈

https://hjho95.tistory.com/18 fetch - GET, application/x-www-form-urlencoded
https://hjho95.tistory.com/19 fetch - POST, application/x-www-form-urlencoded
https://hjho95.tistory.com/20 fetch - POST, application/json

# Vanilla JS 시리즈의 참조 페이지.

MDN fetch: https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch