vue 開發模式跨域解決方案與代理服務器配置
跨域:在瀏覽器里面域名,端口,ip地址,協議,有任何一項不同,則跨域
處理跨域的方式:
jsonp(只能處理get請求),
cors(后端開啟),
代理服務器
在項目目錄下創建vue.config.js.將代理服務器配置放在里面:
目前前端頁面的請求地址為:http://localhost:8080
后端接口地址為:http://localhost:3000
直接發送請求會發生跨域報錯
這個時候就通過前端請求本地服務器代理,然后經過代理請求后台地址實現數據交互
基本用法:
module.exports = { devServer: {
host: 'localhost',
port: 8080, //本地服務器 proxy: { '/api': {
target:'http://localhost:3000', //要請求的后台地址
changeOrigin:true //是否開啟跨域
} } }; 請求到 /api/xxx 現在會被代理到請求 http://localhost:3000/api/xxx, 例如 /api/user 現在會被代理到請求 http://localhost:3000/api/user
代理多個路徑時:
module.exports = { devServer: { proxy: [{ context: ['/auth', '/api'], target: 'http://localhost:3000', }] } }; 如果你想要代碼多個路徑代理到同一個target下, 你可以使用由一個或多個「具有 context 屬性的對象」構成的數組:
去掉api前綴:
module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:3000', pathRewrite: {'^/api' : ''} } } } };
//此時瀏覽器f12的請求接口會顯示是http://localhost:8080/api/user,但是通過代理真實請求地址是 http://localhost:3000/user
忽視https安全提示
module.exports = { devServer: { proxy: { '/api': { target: 'https://other-server.example.com', secure: false } } } }; 默認情況下,不接受運行在 HTTPS 上,且使用了無效證書的后端服務器。如果你想要接受,只要設置 secure: false 就行。修改配置如下:
自定義規則
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'; } } } } } }; 有時你不想代理所有的請求。可以基於一個函數的返回值繞過代理。 在函數中你可以訪問請求體、響應體和代理選項。必須返回 false 或路徑,來跳過代理請求。 例如:對於瀏覽器請求,你想要提供一個 HTML 頁面,但是對於 API 請求則保持代理。你可以這樣做:
跨域
module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, } } } }; 上面的參數列表中有一個changeOrigin參數, 是一個布爾值, 設置為true, 本地就會虛擬一個服務器接收你的請求並代你發送該請求,