๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ‘จ‍๐Ÿ’ป web.dev/fe

storybook middleware proxy ๋กœ CORS ์šฐํšŒํ•˜๊ธฐ

by HandHand 2024. 3. 1.

 

 

fetch ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š” ์ปดํฌ๋„ŒํŠธ ์Šคํ† ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•  ๋•Œ CORS ์ด์Šˆ ํ•ด๊ฒฐ์ด ํ•„์š”ํ–ˆ์Šต๋‹ˆ๋‹ค.

์Šคํ† ๋ฆฌ๋ถ์€ ๋นŒ๋“œ ์‹œ webpack ์„ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๊ณ , dev server ์‹คํ–‰ ์‹œ middleware ์Šคํƒ์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๐Ÿ“Œ storybook middleware ์ถ”๊ฐ€ํ•˜๊ธฐ

์˜ˆ๋ฅผ ๋“ค์–ด ๋‹ค์Œ๊ณผ ๊ฐ™์€ fetch ์š”์ฒญ์ด ์žˆ๊ณ , /api ์— ๋Œ€ํ•œ ํ”„๋ฝ์‹œ๋ฅผ ๊ตฌ์„ฑํ•˜๊ณ  ์‹ถ๋‹ค๊ณ  ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

fetch('/api/blahblah')

 

ํŒจํ‚ค์ง€๋ฅผ ์ถ”๊ฐ€ํ•ด์ค๋‹ˆ๋‹ค.

 

$ npm i -D http-proxy-middleware

 

middleware.js ํŒŒ์ผ์„ ์ƒ์„ฑํ•ด ์ค๋‹ˆ๋‹ค.

target๊ณผ origin์„ ์„ค์ •ํ•ด์„œ ์š”์ฒญ์„ ํ”„๋ก์‹ฑํ•˜๋Š” ๊ทœ์น™์„ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.

 

// .storybook/middleware.js

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function middleware(router) {
  router.use(
    '/api',
    createProxyMiddleware({
      target: 'http://api-gateway',
      changeOrigin: true,
      pathRewrite: { '^/api': '' },
    }),
  );
};

 

์ด์ œ /api ๋กœ ์œ ์ž…๋˜๋Š” ์š”์ฒญ์„ ํ”„๋ฝ์‹œ ํ•ด์„œ origin ์ด ๋ณ€๊ฒฝ๋œ ์š”์ฒญ์œผ๋กœ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค.

  • ๋ณ€๊ฒฝ ์ „: http://localhost:6006/api/product
  • ๋ณ€๊ฒฝ ํ›„: http://api-gateway/product

 

 

๐Ÿ“Œ ์ฐธ๊ณ ์ž๋ฃŒ

Feature: custom proxy settings · Issue #208 · storybookjs/storybook

https://github.com/chimurai/http-proxy-middleware

๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€