Please enable Javascript to view the contents

Vue 開發環境請求代理

· ☕ 1 分钟 · 🐔 Redd Tsai
🏷️
  • #Vue
  • 在前後端分離的環境下,在前端需要和公司後台或第三方 API 溝通時,因為請求來自於不同網域、通訊協定或通訊埠時,而遇到跨來源資源共用(CORS)的問題。如果是在開發時遇到這個問題,可以利用開發環境請求代理來解決。

    vue.config.js

    Vue 透過配置文件(vue.config.js)來設定開發環境請求代理。

    1
    2
    3
    4
    5
    6
    7
    
    module.exports = {
        devServer: {
            proxy: {
                target: 'http://localhost:8080'
            }
        }
    }
    

    這會將任何未知請求代理到 http://localhost:8080。
    也可設定多組代理或使用 websocket。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    module.exports = {
        devServer: {
            proxy: {
                '/ws': {
                    target: 'wss://localhost',
                    ws: true,
                    changeOrigin: true
                }
                '/api': {
                    target: 'http://localhost:8080'
                }
            }
        }
    }
    

    Reference

    Vue CLI devserver

    分享

    蔡文杰
    作者
    Redd Tsai
    Backend Developer