Post

[HTTP] 03. AJAX - 8장. 라이브러리

[HTTP] 03. AJAX - 8장. 라이브러리

03. AJAX


8장. 라이브러리

8-1. SuperAgent

8-2. Axios

8-3. Ky

  • https://github.com/sindresorhus/ky
  • fetch 기반. 2018년 출시. 타입스크립트
  • HTTP 메소드별 전용 함수
  • 프라미스 사용을 간소화
  • Error 클래스를 확장한 HTTPError
  • 훅으로 확장

8-4. Wretch

  • https://github.com/elbywan/wretch
  • fetch 기반. 2017년 출시. 타입스크립트
  • HTTP 메소드별 전용 함수
  • Error 클래스를 확장한 WrechError
  • 미들웨어, 애드온으로 확장

8-5. 중간정리

  • 비슷한 점
    • HTTP 메소드별로 함수를 제공한다
    • 일관된 응답 객체를 제공한다
    • 일관된 오류 객체를 제공한다
    • 구조와 이름만 다를 뿐 확장하는 인터페이스를 제공한다
  • 다른 점
    • SuperAgent: 가장 오래 됨. 크로스브라우저
    • Axios: xhr 기반. 프라이스 인터페이스 제공
    • Ky: fetch 기반. 프라미스 사용 간소화
    • Wretch: 오류 전용 캐처, 미들웨어, 애드온 등 편의 제공

참고


예제

파일구조

  • /ch08
    • public
      • favicon.ico
      • index.html
    • shared
      • serve-static.js
    • server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const fs = require('fs');
const path = require('path');

const serveStatic = (root) => {
  return (req, res) => {
    const filepath = path.join(root, req.url === '/' ? '/index.html' : req.url);

    fs.readFile(filepath, (err, data) => {
      if (err) {
        if (err.code === 'ENOENT') {
          res.statusCode = 404;
          res.write('Not Found\n');
          res.end();
          return;
        }

        res.statusCode = 500;
        res.write('Internal Server Error\n');
        res.end();
        return;
      }

      const ext = path.extname(filepath).toLowerCase();
      let contentType = 'text/html';
      switch (ext) {
        case '.html':
          contentType = 'text/html';
          break;
        case '.js':
          contentType = 'text/javascript';
          break;
        case '.css':
          contentType = 'text/css';
          break;
        case '.png':
          contentType = 'image/png';
          break;
        case '.json':
          contentType = 'application/json';
          break;
        case '.otf':
          contentType = 'font/otf';
          break;
        default:
          contentType = 'application/octet-stream';
      }
      res.setHeader('Content-Type', contentType);

      res.write(data);
      res.end();
    });
  };
};

module.exports = serveStatic;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const http = require('http');
const path = require('path');
const static = require('./shared/serve-static');

const successApi = (req, res) => {
  res.setHeader('Content-type', 'application/json');
  res.write(JSON.stringify({ result: 'success' }));
  res.end();
};

const failApi = (req, res) => {
  res.statusCode = 400;
  res.setHeader('Content-type', 'application/json');
  res.write(JSON.stringify({ result: 'fail' }));
  res.end();
};

const server = http.createServer((req, res) => {
  const { pathname } = new URL(req.url, `http://${req.headers.host}`);

  if (pathname === '/api/success') return successApi(req, res);
  if (pathname === '/api/fail') return failApi(req, res);

  static(path.join(__dirname, 'public'))(req, res);
});

server.listen(3000, () => console.log('server is sunning ::3000'));
This post is licensed under CC BY 4.0 by the author.