11. Axios ๐Ÿ‘ฉโ€๐Ÿ’ป

1. Installation

Axios ๋Š” Promise ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•˜๋Š” HTTP Client๋กœ node.js์™€ Web-browser์—์„œ ๋™์ผํ•œ ์ฝ”๋“œ ๋ฒ ์ด์Šค๋กœ ์ž‘๋™ํ•œ๋‹ค.

  • Server-side : native node.js http module ์„ ์‚ฌ์šฉ.
  • Web-browser : XMLHttpRequests ๋ฅผ ์‚ฌ์šฉ.
npm install axios -S

2. Features

Axios๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค.

  1. ์›น ๋ธŒ๋ผ์šฐ์ €์—์„œ XMLHttpRequests๋ฅผ ์ƒ์„ฑ
  2. node.js ์—์„œ HTTP Requests๋ฅผ ์ƒ์„ฑ
  3. Promise API๋ฅผ ์ง€์›
  4. Request ์™€ Response ์˜ Intercept๋ฅผ ์ง€์›
  5. Request ์™€ Response ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณ€ํ™˜
  6. Request ์˜ ์ทจ์†Œ(cancel) ์ฒ˜๋ฆฌ๋ฅผ ์ง€์›
  7. ์ž๋™์œผ๋กœ JSON ๋ฐ์ดํ„ฐ๋ฅผ ๋ณ€ํ™˜
  8. Client-side ์˜ XSRF์— ๋Œ€ํ•œ ๋ณดํ˜ธ๋ฅผ ์ง€์›

XSRF : CSRF ๋ผ๊ณ ๋„ ๋ถˆ๋ฆฌ๋ฉฐ Cross-site Request Forgery์˜ ์•ฝ์–ด๋‹ค.
cf. ์‚ฌ์ดํŠธ ๊ฐ„ ์š”์ฒญ ์œ„์กฐ

3. Axios Examples

1 ) import library

import axios from "axios"

๋‹จ, TypeScript ์™€ ํ•จ๊ป˜ CommonJS ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•ด์•ผ ์ž๋™์™„์„ฑ๊ณผ intellisense ๊ฐ€ ์ง€์›๋œ๋‹ค.

const axios = require('axios').default;


2 ) Request Get Examples

๋‹ค์Œ 3๊ฐ€์ง€ ๋ฐฉ๋ฒ•์€ ๋ชจ๋‘ ๋™์ผํ•œ ์ž‘์—…์„ ์ฒ˜๋ฆฌํ•œ๋‹ค.

  • Case 1
axios.get('/user?ID=12345')
  .then((response) => {
    // handle success
    console.log(response);
  })
  .catch((error) => {
    // handle error
    console.log(error);
  })
  .then(() => {
    // always executed
  });
  • Case 2
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  })
  .then(() => {
    // always executed
  });  
  • Case 3
const getUser = async () => {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}


3 ) Request Post Examples

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });


4 ) Performing Multiple Concurrent Requests

Axios ๋Š” Promise ๊ธฐ๋ฐ˜์ด๋ฏ€๋กœ, ์—ฌ๋Ÿฌ ์š”์ฒญ์„ ๋™์‹œ์— ๋ณด๋‚ด๋ ค๋ฉด Promise.all() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

const getUserAccount = () => {
  return axios.get('/user/12345');
}

const getUserPermissions = () => {
  return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
  .then((results) => {
    const acct = results[0];
    const perm = results[1];
  });

4. Default Alias Methods

๋ณ„๋„์˜ config ์„ค์ • ์—†์ด ๋ฐ”๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋ณธ ์ œ๊ณต ๋ฉ”์„œ๋“œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด 8๊ฐ€์ง€๊ฐ€ ์กด์žฌํ•œ๋‹ค.

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

์œ„ Alias ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด url, method, data properties ๋ฅผ ๋ช…์‹œํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.

5. Axios Instance

Axios instance ๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด custom config๋ฅผ ์ด์šฉํ•ด new Instance๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ Instance methods๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์œผ๋ฉฐ, Instance config์™€ merge ๋œ๋‹ค.

  • axios#request(config)
  • axios#get(url[, config])
  • axios#delete(url[, config])
  • axios#head(url[, config])
  • axios#options(url[, config])
  • axios#post(url[, data[, config]])
  • axios#put(url[, data[, config]])
  • axios#patch(url[, data[, config]])
  • axios#getUri([config])

6. Request Config

์„ค์ • ๊ฐ€๋Šฅํ•œ config๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์œผ๋ฉฐ, url๋งŒ ํ•„์ˆ˜๊ฐ’์ด๋‹ค. method๋Š” ์ƒ๋žต์‹œ ๊ธฐ๋ณธ๊ฐ’์œผ๋กœ GET์„ ์‚ฌ์šฉํ•œ๋‹ค.

const config = 
{
  url: '/user',
  method: 'get', // default
  baseURL: 'https://some-domain.com/api',

  // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `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
  // NOTE: params that are null or undefined are not rendered in the URL.
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function in charge of serializing `params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `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',

  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000, // default is `0` (no timeout)

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  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

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` allows handling of progress events for uploads
  // browser only
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  // browser only
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
  maxContentLength: 2000,

  // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
  maxBodyLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // `proxy` defines the hostname, port, and protocol of the proxy server.
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  cancelToken: new CancelToken(function (cancel) {
  }),

  // `decompress` indicates whether or not the response body should be decompressed 
  // automatically. If set to `true` will also remove the 'content-encoding' header 
  // from the responses objects of all decompressed responses
  // - Node only (XHR cannot turn off decompression)
  decompress: true // default

}

7. Response Scheme

Response ๋Š” ์•„๋ž˜์™€ ๊ฐ™์€ ๊ตฌ์กฐ๋กœ ๋˜์–ด์žˆ๋‹ค.

const response = 
{
  // `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
  // As of HTTP/2 status text is blank or unsupported.
  // (HTTP/2 RFC: https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.4)
  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: {}
}

8. Overriding Config Defaults

1 ) Library defaults

lib/defaults.js์˜ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๊ธฐ๋ณธ ์„ค์ •๊ฐ’์ด ๊ฐ€์žฅ ๋จผ์ € ์ ์šฉ๋œ๋‹ค.


2 ) Global axios defaults & Custom instance defaults

  • Global axios defaults
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  • Custom instance defaults
// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

์œ„์™€ ๊ฐ™์ด ์ •์˜ํ•œ custom config๊ฐ€ ์กด์žฌํ•  ๊ฒฝ์šฐ, ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๊ธฐ๋ณธ ์„ค์ •๊ฐ’์„ ๋ฎ์–ด์จ ์ „์—ญ ์„ค์ •ํ•œ๋‹ค.


3 ) Config argument for the request

๊ฐ Request ๋ฉ”์„œ๋“œ์— ์ž‘์„ฑํ•œ config๋Š” ํ•ด๋‹น ๋ฉ”์„œ๋“œ์—๋งŒ ์ ์šฉ๋˜๋Š” ์„ค์ •์œผ๋กœ, Inline CSS์™€ ๊ฐ™์ด ๊ฐ€์žฅ ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’๋‹ค.

// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});
  1. ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๊ธฐ๋ณธ๊ฐ’์— ์˜ํ•ด timeout config ๋Š” 0์ด๋‹ค.
  2. Custom instance defaults์— ์˜ํ•ด timeout config ๋Š” 2500์ด ์ „์—ญ์— ์‚ฌ์šฉ๋œ๋‹ค.
  3. ์‹œ๊ฐ„์ด ์˜ค๋ž˜ ๊ฑธ๋ฆฌ๋Š” ์š”์ฒญ์€ ๊ฐœ๋ณ„์ ์œผ๋กœ config๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. ์œ„ /ongRequest์˜ timout config ๋Š” 5000์ด ์‚ฌ์šฉ๋œ๋‹ค.

9. Interceptors

Axios๋ฅผ ์ด์šฉํ•˜๋ฉด ์†์‰ฝ๊ฒŒ Interceptors๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ด๋Š” request ์™€ response ์— ์ ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

1 ) Add Request Interceptors

axios.interceptors.request.use((config) => {
    // Do something before request is sent
    return config;
  }, (error) => {
    // Do something with request error
    return Promise.reject(error);
  });


2 ) Add Response Interceptors

Response๋Š” HTTP status code ๊ฐ€ 2xx์ผ ๋•Œ์™€ ์•„๋‹ ๋•Œ๋กœ ๊ตฌ๋ถ„๋˜์–ด trigger ๋œ๋‹ค.

axios.interceptors.response.use((response) => {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, (error) => {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });


3 ) Remove Interceptors

๋“ฑ๋กํ•œ Interceptors๋ฅผ ์‚ญ์ œํ•˜๋Š” ๋ฐฉ๋ฒ•์€ setTimeout() ๋˜๋Š” setInterval()๋ฅผ ํ•ด์ œ์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋ณ„๋„์˜ ์ƒ์ˆ˜ ๋˜๋Š” ๋ณ€์ˆ˜์— ์ €์žฅ ํ›„ ํ•ด๋‹น ๊ฐ’์„ ์ด์šฉํ•ด ํ•ด์ œ์‹œํ‚จ๋‹ค.

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);


4 ) Add Interceptors to Custom Instance

์ด๋ฏธ ์ƒ์„ฑํ•œ Instance ์— Interceptors๋ฅผ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋‹ค.

const instance = axios.create();
instance.interceptors.request.use(() => {/*...*/});

10. Error Handling

1 ) Split catches

์œ„ 3. Axios Examples ์—์„œ then, catch, then์œผ๋กœ ์ด์–ด์ง€๋Š” ์ฒ˜๋ฆฌ ํ”„๋กœ์„ธ์Šค๋ฅผ ๊ฐ„๋žตํ•˜๊ฒŒ ์„ค๋ช…ํ–ˆ๋‹ค.

๋‹ค์Œ ์ฝ”๋“œ๋Š” ์ด ์ค‘ catch์—์„œ ์•„๋ž˜์™€ ๊ฐ™์ด response ์—๋Ÿฌ > request ์—๋Ÿฌ > ๋ชจ๋“  ์—๋Ÿฌ ์ˆœ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด ์ฒ˜๋ฆฌํ•ด ๋‚˜์•„๊ฐ€๋Š” ์˜ˆ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค. ์ด๋Š” try-catch๋ฅผ ์ด์šฉํ•ด ์—๋Ÿฌ๋ฅผ ๋‹จ๊ณ„๋ณ„๋กœ ๊ตฌ๋ถ„ํ•ด ์ฒ˜๋ฆฌํ•ด ๋‚˜๊ฐ€๋Š” ๊ฒƒ๊ณผ ๊ฐ™์€ ๋ฐฉ์‹์ด๋‹ค.

axios.get('/user/12345')
  .catch((error) => {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });


2 ) Using validateStatus config option

6. Request Config ์˜ validateStatu๋ฅผ ์‚ฌ์šฉํ•ด HTTP status code๋ฅผ ์ผ๋ฐ˜ํ™” ํ•ด ์ •์˜ํ•  ์ˆ˜ ์žˆ๋‹ค.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
})

validateStatus๊ฐ€ true ๋˜๋Š” null ๋˜๋Š” undefined๋ฅผ ์‘๋‹ตํ•˜๋ฉด Promise ๋Š” resolve()๊ฐ€ trigger ๋˜๊ณ , false๋ฅผ ์‘๋‹ตํ•˜๋ฉด reject()๊ฐ€ trigger ๋œ๋‹ค.


3 ) Using toJSON() method

catch์—์„œ HTTP ์—๋Ÿฌ๋ฅผ ์ข€ ๋” ์ž์„ธํ•˜๊ฒŒ ํ™•์ธํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด, toJSON() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
  });

11. Cancellation

2. Features ์—์„œ ์„ค๋ช…ํ•œ Axios๊ฐ€ ์ œ๊ณตํ•˜๋Š” ๊ธฐ๋Šฅ ์ค‘ 6๋ฒˆ์งธ Request ์ทจ์†Œ์— ๋Œ€ํ•œ ์„ค๋ช…์œผ๋กœ, Axios๋Š” Fetch API ๋ฐฉ์‹์˜ ์š”์ฒญ์„ ์ทจ์†Œํ•˜๊ธฐ ์œ„ํ•ด Web APIs - AbortController interface ๋ฅผ ์ง€์›ํ•œ๋‹ค.

์ด๋Š” AbortController instance ๋ฅผ ์ƒ์„ฑํ•ด ์ฒ˜๋ฆฌ๋ฅผ ๊ฐ€๋Šฅ์ผ€ ํ•œ๋‹ค.

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()

CancelToken์ด๋ž€ ๊ฒƒ๋„ ์žˆ๋Š”๋ฐ deprecated ๋˜์—ˆ์œผ๋ฏ€๋กœ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋„๋ก ํ•œ๋‹ค.

12. URL-Encoding Bodies

Axios๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ JavaScript Objects๋ฅผ JSON์œผ๋กœ serializeํ•œ๋‹ค.
๋”ฐ๋ผ์„œ JSON ๋Œ€์‹  application/x-www-form-urlencoded๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ์•„๋ž˜ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

1 ) Using URLSearchParams

Web APIs - URLSearchParams ๋ฅผ ์ด์šฉํ•œ๋‹ค.

๋‹ค์Œ 3๊ฐ€์ง€ ๋ฐฉ๋ฒ•์€ ๋ชจ๋‘ ๋™์ผํ•œ ์ž‘์—…์„ ์ฒ˜๋ฆฌํ•œ๋‹ค.

  • Case 1
const paramsString = 'foo=bar&baz=qoo';
const searchParams = new URLSearchParams(paramsString);
axios.post('/foo', searchParams);
  • Case 2
const searchParams = new URLSearchParams();
searchParams.append('foo', 'bar');
searchParams.append('baz', 'qoo');
axios.post('/foo', searchParams);
  • Case 3
const paramsObj = { foo: 'bar', baz: 'qoo' };
const searchParams = new URLSearchParams(paramsObj);
axios.post('/foo', searchParams);


2 ) Using qs library

๋‹ค์Œ 2๊ฐ€์ง€ ๋ฐฉ๋ฒ•์€ ๋ชจ๋‘ ๋™์ผํ•œ ์ž‘์—…์„ ์ฒ˜๋ฆฌํ•œ๋‹ค.

  • Case 1
const qs = require('qs');
axios.post('/foo', qs.stringify({ foo: 'bar', baz: 'qoo' }));
  • Case 2
import qs from 'qs';
const data = { foo: 'bar', baz: 'qoo' };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

12. Axios Examples ๐Ÿ‘ฉโ€๐Ÿ’ป

1. Create Mock API for Axios Examples

Mock ์„œ๋ฒ„๋ฅผ ํ†ตํ•œ ํ…Œ์ŠคํŠธ๋ฅผ ์ง„ํ–‰ํ•˜๊ธฐ ์œ„ํ•ด Postman ์— Mock ์„œ๋ฒ„์™€ GET /test ๋ฅผ ์ƒ์„ฑ ํ›„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด example๊ณผ Tests๋ฅผ ๋“ฑ๋กํ•œ๋‹ค.

  • example

Postman - example data

[
    {"productName": "iPhone 14 Pro Max", "price": 1750000, "category": "Phone"},
    {"productName": "iPhone 14 Pro", "price": 1550000, "category": "Phone"},
    {"productName": "iPhone 14 Plus", "price": 1350000, "category": "Phone"},
    {"productName": "iPhone 14", "price": 1250000, "category": "Phone"},
    {"productName": "MacBook Pro 16", "price": 3360000, "category": "Laptop"},
    {"productName": "MacBook Pro 14", "price": 2690000, "category": "Laptop"},
    {"productName": "iPad Pro 12.9", "price": 1729000, "category": "Tablet"},
    {"productName": "iPad Pro 11", "price": 1249000, "category": "Tablet"}
]


  • Tests

Postman - test code

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
pm.test("Get /test JSON data is correct", function () {
    const expect = [
        { "productName": "iPhone 14 Pro Max", "price": 1750000, "category": "Phone" },
        { "productName": "iPhone 14 Pro", "price": 1550000, "category": "Phone" },
        { "productName": "iPhone 14 Plus", "price": 1350000, "category": "Phone" },
        { "productName": "iPhone 14", "price": 1250000, "category": "Phone" },
        { "productName": "MacBook Pro 16", "price": 3360000, "category": "Laptop" },
        { "productName": "MacBook Pro 14", "price": 2690000, "category": "Laptop" },
        { "productName": "iPad Pro 12.9", "price": 1729000, "category": "Tablet" },
        { "productName": "iPad Pro 11", "price": 1249000, "category": "Tablet" }
    ]
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.eql(expect);
});


Collection์˜ โˆ™โˆ™โˆ™ ๋ฅผ ๋ˆ„๋ฅด๊ณ  Run collection์„ ํ†ตํ•ด Mock API๊ฐ€ ์ •์ƒ ์ž‘๋™ํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.

Postman - test result

2. Axios Examples with mixins.js

Axios๋ฅผ ์ด์šฉํ•ด ๋ณด๋‚ด๋Š” XHR ์š”์ฒญ์„ ๊ณตํ†ต์œผ๋กœ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด mixins.jsํŒŒ์ผ์„ ์ƒ์„ฑํ•˜๊ณ , ์—ฌ๊ธฐ์— ๊ณตํ†ต์œผ๋กœ ์‚ฌ์šฉํ•  ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•œ๋‹ค.

mixins ์— ๋Œ€ํ•œ ์ž์„ธํ•œ ์„ค๋ช…์€ mixins ๋ฅผ ์ฐธ๊ณ ํ•œ๋‹ค.

  • /src/mixins.js
import axios from "axios";

export default {
  methods: {
    async $api(url, method, data) {
      return (
        await axios({
          url: url,
          baseURL: "https://0000.mock.pstmn.io",
          method: method,
          data: data,
        }).catch((e) => {
          console.log(e);
        })
      ).data;
    },
  },
};

๊ทธ๋ฆฌ๊ณ  ์œ„ mixins๋ฅผ Vue instance ์— ๋“ฑ๋กํ•œ๋‹ค.

  • /src/main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import mixins from "@/mixins";

createApp(App).use(store).use(router).mixin(mixins).mount("#app");


์ƒˆ View ํŽ˜์ด์ง€๋ฅผ ๋งŒ๋“ค๊ณ  Axios๋ฅผ ์ด์šฉํ•ด Mock API๋กœ๋ถ€ํ„ฐ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›์•„์™€ ํ‘œ๋กœ ๋ Œ๋”๋ง์„ ํ•ด๋ณด์ž.

  • /src/views/AxiosTestView.vue
<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>์ œํ’ˆ๋ช…</th>
          <th>๊ฐ€๊ฒฉ</th>
          <th>์นดํ…Œ๊ณ ๋ฆฌ</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(product, i) in productList" :key="i">
          <td>{{ product.productName }}</td>
          <td>{{ product.price }}</td>
          <td>{{ product.category }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  name: "AxiosTestView",
  data() {
    return {
      productList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      this.productList = await this.$api("/test", "get");
    },
  },
};
</script>

<style scoped>
table {
  font-family: Arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #ddd;
  text-align: left;
  padding: 8px;
}
</style>

Axios Example Result

3. Refactor Axios with DTO Objects

<template>
  <tr v-for="(product, i) in productList" :key="i">
    <td></td>
    <td></td>
    <td></td>
  </tr>
</template>

TypeScript ๊ฐ€ ์•„๋‹Œ JavaScript ๋ฅผ ์‚ฌ์šฉ์ค‘์ผ ๋•Œ productList ์˜ ํƒ€์ž…์„ ๋ฏธ๋ฆฌ ์ •ํ•  ์ˆ˜ ์—†๋‹ค. ์ธ์Šคํ„ด์Šค๊ฐ€ ์ƒ์„ฑ๋˜๋ฉฐ Type Inference๋ฅผ ํ†ตํ•ด์„œ๋งŒ ํƒ€์ž…์ด ์ •ํ•ด์ง€๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋”ฐ๋ผ์„œ ํƒ€์ž…์„ ๋ฏธ๋ฆฌ ์•Œ ์ˆ˜ ์—†์œผ๋‹ˆ IDE์˜ Intellisense๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์–ด ์ฝ”๋“œ ์ž‘์„ฑ์ด ์–ด๋ ค์šธ ๋ฟ ์•„๋‹ˆ๋ผ ํœด๋จผ ์—๋Ÿฌ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋Š” ์š”์ธ์ด ๋œ๋‹ค.

๋”ฐ๋ผ์„œ TypeScript ๊ฐ€ ์•„๋‹Œ JavaScript ์˜ ํ•œ๊ณ„๋ฅผ ๊ทน๋ณตํ•˜๊ธฐ ์œ„ํ•ด ์•„๋ž˜์™€ ๊ฐ™์ด ํƒ€์ž… ์ถ”๋ก ์— ์˜ํ•ด ๊ฐ์ฒด์˜ ํƒ€์ž…์ด ์ง€์ •๋˜๋„๋ก ์ดˆ๊ธฐํ™” ํ›„ ๋ฐ์ดํ„ฐ๋ฅผ ๊ต์ฒดํ•˜๋Š” Trick์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

const product = {
  productName: "",
  price: 0,
  category: ""
}

let productList = new Array(product)
// let productList = Array["product"]

const response = [
  {productName: "Choco Pie", price: 2000, category: "Snack"},
  {productName: "Oh Yes", price: 2400, category: "Snack"},
  {productName: "Sprite", price: 1200, category: "Beverage"}
]

productList = response

for (const product of productList) {
  console.log(`${product.productName} is ${product.price > 2000 ? 'over' : 'less'} than 2000 won.`)
}
Choco Pie is less than 2000 won.
Oh Yes is over than 2000 won.
Sprite is less than 2000 won.


์œ„ ์˜ˆ์ œ์˜ mixins.js๋ฅผ Axios Default Alias Methods๋ฅผ ์‚ฌ์šฉํ•˜๋„๋ก ๋ฆฌํŒฉํ† ๋ง ํ•˜๊ณ , productList Array ์˜ ํƒ€์ž…์„ ๋ฏธ๋ฆฌ ์ง€์ •ํ•ด JavaScript ์˜ IDE์˜ Intellisense๊ฐ€ ์ด๋ฅผ ์ธ์‹ํ•˜๋„๋ก ๋ณ€๊ฒฝํ•ด๋ณด์ž.

  • /src/mixins.js
import axios from "axios";

export default {
  created: function () {
    this.$api = axios.create({
      baseURL: "https://0000.mock.pstmn.io",
    });
  },
  methods: {
    $get: async function (url, data) {
      return await this.$api
        .get(url, data)
        .then((res) => res.data)
        .catch((e) => console.log(e));
    },
    $post: async function (url, data) {
      return await this.$api
        .post(url, data)
        .then((res) => res.data)
        .catch((e) => console.log(e));
    },
    $put: async function (url, data) {
      return await this.$api
        .put(url, data)
        .then((res) => res.data)
        .catch((e) => console.log(e));
    },
    $patch: async function (url, data) {
      return await this.$api
        .patch(url, data)
        .then((res) => res.data)
        .catch((e) => console.log(e));
    },
    $delete: async function (url, data) {
      return await this.$api
        .delete(url, data)
        .then((res) => res.data)
        .catch((e) => console.log(e));
    },
  },
};

์ด์ œ this.$api.get(...) ๊ณผ ๊ฐ™์ด ๊ธฐ๋ณธ config๋ฅผ ํฌํ•จํ•œ instance ์— ์ผ๋ถ€ config ๋ฅผ ์ˆ˜์ •ํ•ด Custom Request ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์„ ๋ฟ ์•„๋‹ˆ๋ผ, this.$get(url, data)์™€ ๊ฐ™์ด ๋ณ„๋„์˜ ์„ค์ • ์—†์ด ๊ณตํ†ต์œผ๋กœ ์„ค์ •ํ•œ ๊ธฐ๋ณธ config ๊ฐ€ ์ ์šฉ๋œ Axios Default Alias Methods๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค.

  • /src/views/AxiosTestView.vue
<script>
export default {
  name: "AxiosTestView",
  data() {
    return {
      productList: Array["product"],
      product: {
        productName: "",
        price: 0,
        category: "",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      this.productList = await this.$get("/test");
    },
  },
};
</script>

๋‹จ, Vue์˜ data() Closure๋Š” Vanilla JS์—์„œ ์‚ฌ์šฉํ•œ ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์˜ Trick๊ณผ๋Š” ๋‹ฌ๋ฆฌ new Array(product)๋Š” ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๊ณ , Array["product"]๋งŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

4. Refactor Axios with DTO Classes

์œ„์™€ ๊ฐ™์ด Options API ๋‚ด์˜ data ๋ฅผ ์ด์šฉํ•ด Object๋ฅผ DTO๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ๋‹ค๋ฅธ Component ์—์„œ ์žฌ์‚ฌ์šฉ ํ•  ์ˆ˜ ์—†๋‹ค. ๋˜ํ•œ, ํ•„์š”์— ๋”ฐ๋ผ Getter/Setter๋ฅผ ๋งŒ๋“ค๊ฑฐ๋‚˜ ์ œ์•ฝ์„ ์œ„ํ•ด Wrapper๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋“ฑ ์ถ”๊ฐ€์ ์ธ ์ฒ˜๋ฆฌ๋ฅผ ์ฝ”๋“œ ๋ถ„ํ•˜๊ธฐ๊ฐ€ ํž˜๋“ค๋‹ค. ๋”ฐ๋ผ์„œ ์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š” ์ด๋Ÿฐ Entities๋Š” Vue ํŒŒ์ผ์ด ์•„๋‹Œ ๋ณ„๋„์˜ JavaScript ํŒŒ์ผ๋กœ ๋ถ„๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋‹จ์ˆœ Object ๋ณด๋‹ค๋Š” ์ข€ ๋” ๊ธฐ๋Šฅ์ด ๋งŽ์€ Class๋ฅผ ์ด์šฉํ•ด DTO๋ฅผ ๋งŒ๋“ค์–ด ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.

  • /src/dto/Product.js
export default class Product {
  productName;
  price;
  category;

  constructor(productName, price, category) {
    this._productName = productName;
    this._price = price;
    this._category = category;
  }
}
  • /src/views/AxiosTestView.vue
<script>
import Product from "@/dto/Product";

export default {
  name: "AxiosTestView",
  data() {
    return {
      productList: Array[Product],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      this.productList = await this.$get("/test");
    },
  },
};
</script>




Reference

  1. ๊ณ ์Šน์›. Vue.js ํ”„๋กœ์ ํŠธ ํˆฌ์ž… ์ผ์ฃผ์ผ ์ „. ๋น„์ œ์ดํผ๋ธ”๋ฆญ Chapter 7, 2021.
  2. โ€œAxios.โ€ Axios Documents, accessed Dec. 29, 2022, Axios.
  3. โ€œ์‚ฌ์ดํŠธ ๊ฐ„ ์š”์ฒญ ์œ„์กฐ.โ€ ์œ„ํ‚ค๋ฐฑ๊ณผ, Fab. 6, 2022, accessed Dec. 29, 2022, ์‚ฌ์ดํŠธ ๊ฐ„ ์š”์ฒญ ์œ„์กฐ.
  4. โ€œAbortController.โ€ MND, Oct. 10, 2022, accessed Dec. 29, 2022, Web APIs - AbortController.
  5. โ€œURLSearchParams.โ€ MND, Oct. 10, 2022, accessed Dec. 29, 2022, Web APIs - URLSearchParams.