본문으로 바로가기

목차

    1. axios.js

    • Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리입니다.
    • Ajax, fetch와 같은 웹 통신 기능을 제공하는 라이브러리입니다.
    • HTTP 요청 취소 및 요청과 응답을 JSON 형태로 자동으로 변경해 줍니다.
    • 브라우저 호환성이 뛰어납니다.

    1.1. 설치

    Using npm:
    $ npm install axios
    
    Using bower:
    $ bower install axios
    
    Using yarn:
    $ yarn add axios
    
    Using jsDelivr CDN:
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
    Using unpkg CDN:
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    1.2. 기본 형태

    • GET, POST, Other Http Method

    1.2.1. GET

    axios.get('/test?name=veneas')
    .then(function (response) {
    	// 성공한 경우 실행
    	console.log(response);
    })
    .catch(function (error) {
    	// 에러인 경우 실행
    	console.log(error);
    })
    .then(function () {
    	// 항상 실행
    });
    axios.get('/test', {
    	params: {
    		name: 'veneas'
    	}
    })
    .then(function (response) {
    	console.log(response);
    })
    .catch(function (error) {
    	console.log(error);
    });
    axios({
    	method: 'get',
    	url: '/test?name=veneas'
    })
    .then(function (response) {
    	console.log(response);
    })
    .catch(function (error) {
    	console.log(error);
    });
    axios({
    	method: 'get',
    	url: '/test',
    	params: {
    		name: 'veneas'
    	}
    })
    .then(function (response) {
    	console.log(response);
    })
    .catch(function (error) {
    	console.log(error);
    });

    1.2.2. POST

    Request Data) Content-Type: application/json

    axios.post('/test', 
    	{
    		name: 'venese'
    	}
    )
    .then(function (response) {
    	console.log(response);
    })
    .catch(function (error) {
    	console.log(error);
    });
    axios({
    	url: '/test',
    	method: 'post',
    	data: {
    		name: 'veneas'	
    	}
    })
    .then(function a(response) { 
    	console.log(response) 
    })
    .catch(function (error) {
    	console.log(error);
    });

    Request Data) Content-Type: multipart/form-data

    const form = new FormData();
    form.append('name', 'veneas');
    	
    axios.post('/test', form).then(function (response) {
    	console.log(response)		
    })
    .catch(function (error) {
    	console.log(error);
    });
    const form = new FormData();
    form.append('name', 'veneas');
    
    axios({
    	url: '/test',
    	method: 'post',
    	data: form
    })
    .then(function a(response) { 
    	console.log(response) 
    })
    .catch(function (error) {
    	console.log(error);
    });

    1.2.3. Other Http Method

    axios.head(url[, config])
    axios.delete(url[, config])
    axios.options(url[, config])
    axios.put(url[, data[, config]])
    axios.patch(url[, data[, config]])

    1.2. Request 설정

    {
      // `url` is the server URL that will be used for the request
      url: '/user',
    
      // `method` is the request method to be used when making the request
      method: 'get', // default
    
      // `baseURL` will be prepended to `url` unless `url` is absolute.
      // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
      // to methods of that instance.
      baseURL: 'https://some-domain.com/api/',
    
      // `headers` are custom headers to be sent
      headers: {'X-Requested-With': 'XMLHttpRequest'},
    
      // `params` are the URL parameters to be sent with the request
      // Must be a plain object or a URLSearchParams object
      params: {
        ID: 12345
      },
    
      // `data` is the data to be sent as the request body
      // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
      // When no `transformRequest` is set, must be of one of the following types:
      // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
      // - Browser only: FormData, File, Blob
      // - Node only: Stream, Buffer
      data: {
        firstName: 'Fred'
      },
    
      // syntax alternative to send data into the body
      // method post
      // only the value is sent, not the key
      data: 'Country=Brasil&City=Belo Horizonte',
    
      // HTTP Basic 인증
      // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
      // This will set an `Authorization` header, overwriting any existing
      // `Authorization` custom headers you have set using `headers`.
      // Please note that only HTTP Basic auth is configurable through this parameter.
      // For Bearer tokens and such, use `Authorization` custom headers instead.
      auth: {
        username: 'janedoe',
        password: 's00pers3cret'
      },
    
      // `responseType` indicates the type of data that the server will respond with
      // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
      //   browser only: 'blob'
      responseType: 'json', // default
    
      // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
      // Note: Ignored for `responseType` of 'stream' or client-side requests
      responseEncoding: 'utf8', // default
    
    }

     

    1.3. 응답 스키마

    {
      // `data` is the response that was provided by the server
      data: {},
    
      // `status` is the HTTP status code from the server response
      status: 200,
    
      // `statusText` is the HTTP status message from the server response
      statusText: 'OK',
    
      // `headers` the HTTP headers that the server responded with
      // All header names are lower cased and can be accessed using the bracket notation.
      // Example: `response.headers['content-type']`
      headers: {},
    
      // `config` is the config that was provided to `axios` for the request
      config: {},
    
      // `request` is the request that generated this response
      // It is the last ClientRequest instance in node.js (in redirects)
      // and an XMLHttpRequest instance in the browser
      request: {}
    }

     

     


    2. axios.js + Spring 컨트롤러 예시

    • 클라이언트(axios.js), 서버(Spring) 간 간단한 데이터 통신 예시입니다.

    2.1. GET

    백엔드(서버)

    @GetMapping("/test")
    public ArrayList<HashMap<String, Object>> test(HttpServletRequest req) throws Exception{
    
    	//response Data
    	ArrayList<HashMap<String, Object>> rtnArray = new ArrayList<HashMap<String, Object>>();
    	HashMap<String, Object> rtnMap = new HashMap<String, Object>();
    
    	rtnMap.put("requestData1", req.getParameter("name"));
    	rtnMap.put("requestData2", req.getParameter("food"));
    	rtnArray.add(rtnMap);
    
    	return rtnArray; 
    }

     

    프론트(클라이언트)

    • get 방식은 http body가 없으므로 요청할 데이터를 params을 사용하거나 url뒤에 붙여줍니다.
    axios({
    	method: 'get',
    	url: '/test',
    	params: {
    		name: 'veneas',
            food: 'apple'
    	}
    })
    .then(function (response) {
    	console.log(response);
    })
    .catch(function (error) {
    	console.log(error);
    });

     

    실행 결과

    • 웹브라우저 개발자 도구의 콘솔을 이용해 실행해봅니다.

    실행 결과 GET

    2.2. POST(application/json)

    백엔드(서버)

    @PostMapping("/test")
    public ArrayList<HashMap<String, Object>> test(@RequestBody HashMap<String, Object> requestJsonHashMap) throws Exception{
    
    	//response Data
    	ArrayList<HashMap<String, Object>> rtnArray = new ArrayList<HashMap<String, Object>>();
    	HashMap<String, Object> rtnMap = new HashMap<String, Object>();
    
    	rtnMap.put("requestData1", requestJsonHashMap.get("name"));
    	rtnMap.put("requestData2", requestJsonHashMap.get("food"));        
    	rtnArray.add(rtnMap);
    
    	return rtnArray; 
    }

    프론트(클라이언트)

    axios({
    	url: '/test',
    	method: 'post',
    	data: {
    		name: 'veneas',
            food: 'pizza'
    	}
    })
    .then(function a(response) { 
    	console.log(response) 
    })
    .catch(function (error) {
    	console.log(error);
    });

    실행결과

    실행 결과 POST(JSON)

    2.3. POST(multipart/form-data)

    백엔드(서버)

    @PostMapping("/test")
    public ArrayList<HashMap<String, Object>> test(HttpServletRequest req) throws Exception{
    
    	//response Data
    	ArrayList<HashMap<String, Object>> rtnArray = new ArrayList<HashMap<String, Object>>();
    	HashMap<String, Object> rtnMap = new HashMap<String, Object>();
    
    	rtnMap.put("requestData1", req.getParameter("name"));
    	rtnMap.put("requestData2", req.getParameter("food"));
    	rtnArray.add(rtnMap);
    
    	return rtnArray; 
    }

    프론트(클라이언트)

    const form = new FormData();
    form.append('name', 'veneas');
    form.append('food', 'cake');
    
    axios({
    	url: '/test',
    	method: 'post',
    	data: form
    })
    .then(function a(response) { 
    	console.log(response) 
    })
    .catch(function (error) {
    	console.log(error);
    });

    실행결과

    실행 결과 POST(form)