6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Storybookで他のサーバにリクエストをプロキシ(Proxy)する方法

Posted at

Storybook を用いたフロントエンドの開発で、
一部のリクエストのみ、別サーバーへプロキシする(リクエストを転送する)方法が少し変わっていたので、その備忘録です。

WebpackDevServerの設定ではできない😨?

WebpackDevServerのプロキシは、 proxyパラメータを介して設定することができます。
APIクライアントを開発する場合にはとても便利な機能ですね😇

/apiへのリクエストを他のサーバーへプロキシする設定は、以下の通り。

webpack.config.js
  devServer: {
    proxy: {
      "^/api": {
        target: "https://api-endpoint.com",
        changeOrigin: true
      }
    },

しかし、プロキシを追加してみても、うまくいかない。。。😫😫😫

middleware.js を追加して機能を拡張する!😇

Storybook には柔軟なミドルウェアの拡張機能があります。
「Storybook のconfigフォルダにmiddleware.jsを追加」することで、
ルーティングの過程に何らかの処理を差し込むことができます!

WebpackDevServerを直接使用せず、プロキシサーバーをカスタマイズするためには
以下のようなmiddleware.jsファイルを置きます。

middleware.js

const proxy = require("http-proxy-middleware");

module.exports = router =>
  router.use(
    "^/api",
    proxy({
      target: "https://api-endpoint.com",
      changeOrigin: true
    })
  );

※注意点、ターゲットURLに変更するには、changeOriginオプションを明示的にtrueに設定する必要があるみたいです!

簡単にプロキシミドルウェアを設定できる
http-proxy-middlewareパッケージを使っています✌️

$ yarn add -D http-proxy-middleware

まとめ

Storybook にこんな便利なミドルウェアのカスタム設定があることを知ったと同時に、
Express で作られていることを今更ながら知りました😭

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?