Footnotes
-
Preflighted requests | MDN: “Unlike simple requests, for “preflighted” requests the browser first sends an HTTP request using the OPTIONS method to the resource on the other origin, in order to determine if the actual request is safe to send.“ ↩
-
CloudFront 배포의 캐시 동작이 HTTP 요청에 대한 OPTIONS 메서드를 허용함: “CloudFront는 기본적으로 GET 및 HEAD 메서드만 허용합니다.” ↩
const formData = new FormData();
const single = document.querySelector('input[type="file"]');
const multiple = document.querySelector('input[type="file"][multiple]');
formData.append('single', single.files[0]);
[...multiple.files].forEach((file, index) => {
formData.append(`multiple_${index}`, file);
})
fetch('https://example.com/posts', {
method: 'POST',
body: formData,
})
이미지 다운로드 구현. 이미지 응답값을 buffer로 변환해서 파일쓰기로 저장한다.
const fs = require('fs')
const path = require('path')
const util = require('util')
const fetch = require('node-fetch')
const writeFile = util.promisify(fs.writeFile)
const mkdir = util.promisify(fs.mkdir)
const FOLDER_PATH = 'FOLDER_PATH'
async function download({ url }) {
const response = await fetch(url)
const buffer = Buffer.from(await response.arrayBuffer())
if (!fs.existsSync(FOLDER_PATH)) {
await mkdir(FOLDER_PATH)
}
await writeFile(path.join(FOLDER_PATH, path.basename(new URL(url).pathname)), buffer)
}
서비스워커로 fetch를 감지해서 respondWith로 응답을 직접 주는1 방식으로 mock 을 구현한다는 내용.
개인적으로는 mock은 간단하게 구현 가능할 것 같은데 이미 같은 기능의 잘 만들어진 라이브러리들이 있으니까 아이디어 정도로 생각하면 될 것 같다.
addEventListener('fetch', e => {
// e.request
// e.respondWith
})
- How To Run a Proxy Server Inside Your Browser | by Danny Moerkerke | Better Programming
- MSW – Seamless API mocking library for browser and Node | Mock Service Worker
서비스워커는 브라우저에서 나가는 요청만 본다2. SSR(getServerSideProps)처럼 서버에서 나가는 요청은 Node 쪽에서 가로챈다.
Footnotes
-
FetchEvent.respondWith() | MDN: “prevents the browser’s default fetch handling, and allows you to provide a promise for a Response yourself.” ↩
-
Service Worker API | MDN: “Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available).” ↩