Webpack-dev-server的proxy用法(請求轉發解決跨域問題)

前言

  1. 如果你有單獨的後端開發服務器 API,並且希望在同域名下發送 API 請求 ,那麼代理某些 URL 會很有用。
  2. 解決開發環境的跨域問題(不用在去配置nginx和host, 爽歪歪~~)

webpack.config.js中配置

下面簡單介紹一下五個經常使用的場景

使用一:

mmodule.exports = {
    //...
    devServer: {
        proxy: {
            '/api': 'http://localhost:3000'
        }
    }
};

請求到 /api/xxx 現在會被代理到請求 http://localhost:3000/api/xxx, 例如 /api/user 現在會被代理到請求 http://localhost:3000/api/user

使用二

如果你想要代碼多個路徑代理到同一個target下, 你可以使用由一個或多個「具有 context 屬性的對象」構成的數組:

module.exports = {
    //...
    devServer: {
        proxy: [{
            context: ['/auth', '/api'],
            target: 'http://localhost:3000',
        }]
    }
};

使用三:

如果你不想始終傳遞 /api ,則需要重寫路徑:

module.exports = {
    //...
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:3000',
                pathRewrite: {'^/api' : ''}
            }
        }
    }
};

請求到 /api/xxx 現在會被代理到請求 http://localhost:3000/xxx, 例如 /api/user 現在會被代理到請求 http://localhost:3000/user

使用四:

默認情況下,不接受運行在 HTTPS 上,且使用了無效證書的後端服務器。如果你想要接受,只要設置 secure: false 就行。修改配置如下:

module.exports = {
    //...
    devServer: {
        proxy: {
            '/api': {
                target: 'https://other-server.example.com',
                secure: false
            }
        }
    }
};

使用五:

有時你不想代理所有的請求。可以基於一個函數的返回值繞過代理。
在函數中你可以訪問請求體、響應體和代理選項。必須返回 false 或路徑,來跳過代理請求。

例如:對於瀏覽器請求,你想要提供一個 HTML 頁面,但是對於 API 請求則保持代理。你可以這樣做:

module.exports = {
  //...
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:3000',
                bypass: function(req, res, proxyOptions) {
                    if (req.headers.accept.indexOf('html') !== -1) {
                        console.log('Skipping proxy for browser request.');
                        return '/index.html';
                    }
                }
            }
        }
    }   
};

解決跨域原理

上面的參數列表中有一個changeOrigin參數, 是一個布爾值, 設置爲true, 本地就會虛擬一個服務器接收你的請求並代你發送該請求,

module.exports = {
    //...
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:3000',
                changeOrigin: true,
            }
        }
    }
};

vue-cli中proxyTable配置接口地址代理示例

修改 config/index.js

module.exports = {
    dev: {
    // 靜態資源文件夾
    assetsSubDirectory: 'static',
    // 發佈路徑
    assetsPublicPath: '/',

    // 代理配置表,在這裏可以配置特定的請求代理到對應的API接口
    // 使用方法:https://vuejs-templates.github.io/webpack/proxy.html
    proxyTable: {
        // 例如將'localhost:8080/api/xxx'代理到'https://wangyaxing.cn/api/xxx'
        '/api': {
            target: 'https://wangyaxing.cn', // 接口的域名
            secure: false,  // 如果是https接口,需要配置這個參數
            changeOrigin: true, // 如果接口跨域,需要進行這個參數配置
        },
        // 例如將'localhost:8080/img/xxx'代理到'https://cdn.wangyaxing.cn/xxx'
        '/img': {
            target: 'https://cdn.wangyaxing.cn', // 接口的域名
            secure: false,  // 如果是https接口,需要配置這個參數
            changeOrigin: true, // 如果接口跨域,需要進行這個參數配置
            pathRewrite: {'^/img': ''}  // pathRewrite 來重寫地址,將前綴 '/api' 轉爲 '/'。
        }
    },
    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 4200, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
}

更多參數

dev-server 使用了非常強大的 http-proxy-middleware , http-proxy-middleware 基於 http-proxy 實現的,可以查看 http-proxy 的源碼和文檔:https://github.com/nodejitsu/node-http-proxy 。

target:要使用url模塊解析的url字符串
forward:要使用url模塊解析的url字符串
agent:要傳遞給http(s).request的對象(請參閱Node的https代理和http代理對象)
ssl:要傳遞給https.createServer()的對象
ws:true / false,是否代理websockets
xfwd:true / false,添加x-forward標頭
secure:true / false,是否驗證SSL Certs
toProxy:true / false,傳遞絕對URL作爲路徑(對代理代理很有用)
prependPath:true / false,默認值:true - 指定是否要將目標的路徑添加到代理路徑
ignorePath:true / false,默認值:false - 指定是否要忽略傳入請求的代理路徑(注意:如果需要,您必須附加/手動)。
localAddress:要爲傳出連接綁定的本地接口字符串
changeOrigin:true / false,默認值:false - 將主機標頭的原點更改爲目標URL

使用中的注意要點:

使用fastmock模擬後端接口時,發現同樣的三個接口,其中一個可以代理,另外兩個不能代理,讓人不能理解,具體配置方式如下所示:

devServer: {
        // development server port 8000
        port: '8000', // 開發模式默認端口
        proxy: {
            '/api': {
                target: 'http://10.203.13.66:8030', //實際的api地址
                ws: false,
                changeOrigin: true,
                pathRewrite: {
                    '^/api': '/'
                }
            },
            '/ceshi': {
                target: 'https://www.fastmock.site/mock/e35a162557a2455f8ba553a72aae693c',
                ws: false,
                changeOrigin: true,
                pathRewrite: {
                    '/ceshi': '/'
                }
            }
        }
    },

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章