1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Viteの開発サーバーでProxy(プロキシ)を設定してCORSエラーを回避する方法

1
Posted at

はじめに

Vite でフロントエンドの開発をしている際、別ドメインや別ポートで動いているバックエンド API を叩こうとすると CORS(Cross-Origin Resource Sharing)制限 に直面することがあります。

これを解決する最も手軽な方法が、Vite 開発サーバーのプロキシ機能を使うことです。vite.config.js(または .ts)の server.proxy オプションを設定することで、ブラウザからのリクエストを Vite サーバーが中継し、バックエンドへ転送してくれます。

基本的な設定例

最もシンプルな設定は、特定のパス(例: /api)で始まるリクエストを別のサーバーに転送するものです。

// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    proxy: {
      // 文字列による簡略設定(/api/foo -> http://localhost:4567/api/foo)
      '/api': 'http://localhost:4567',

      // オプションを用いた詳細設定
      '/v1': {
        target: 'http://typicode.com',
        changeOrigin: true, // ホストヘッダーの起点をターゲット URL に変更
        rewrite: (path) => path.replace(/^\/v1/, ''), // パスから /v1 を削除して転送
      },
    },
  },
})

環境

  • vite 4.0.5
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?