跨域資源請求
Vue資源服務器請求遇到常見的跨域資源請求時A-C-A-O,用Vue腳手架搭建的其實也是Node服務器環境.運行時僅僅只是將項目打包至內存環境下,然后瀏覽器運行該項目.若后端沒有使用Cors中間件.則可以使用Proxy.
根目錄創建 vue.config.js
vue.config.js
是一個可選的配置文件,如果項目的 (和 package.json
同級的) 根目錄中存在這個文件,那么它會被 @vue/cli-service
自動加載。你也可以使用 package.json
中的 vue
字段,但是注意這種寫法需要你嚴格遵照 JSON 的格式來寫。
具體配置信息
module.exports={
代理一個服務器
devServer:{
proxy: 'http://localhost:3000', ->告訴開發服務器將任何未知請求 (沒有匹配到靜態文件的請求) 代理到http://localhost:3000。
host: '0.0.0.0',
port: 8003, ->本地
open: true,
https: false,
proxy: null, // string | Object
},
lintOnSave:false, //關閉esling警告
lintOnSave: process.env.NODE_ENV !== 'production', //生產構建時禁用
productionSourceMap:false, //打包不攜帶map文件
cli3 代理多個服務器
proxy:{//代理是從指定的target后面開始匹配的,不是任意位置;配置pathRewrite可以做替換
'/api':{//axios訪問 /api == target + /api
target:'https://localhost:3000',
changeOrigin:true,//創建虛擬服務器
ws:true,//websocket代理
},
'/douban':{// axios 訪問 /douban == target + '/douban'
target:'https://api.douban.com',
changeOrigin:true,
pathRewrite:{//路徑替換
'^/douban':'',// axios 訪問/douban/v2 == target + /v2
}
}
}
}
官方文檔
devServer.proxy
-
Type:
string | Object
如果你的前端應用和后端 API 服務器沒有運行在同一個主機上,你需要在開發環境下將 API 請求代理到 API 服務器。這個問題可以通過
vue.config.js
中的devServer.proxy
選項來配置。devServer.proxy
可以是一個指向開發環境 API 服務器的字符串:module.exports = { devServer: { proxy: 'http://localhost:4000' } }
這會告訴開發服務器將任何未知請求 (沒有匹配到靜態文件的請求) 代理到
http://localhost:4000
。如果你想要更多的代理控制行為,也可以使用一個
path: options
成對的對象。完整的選項可以查閱 http-proxy-middleware 。module.exports = { devServer: { proxy: { '/api': { target: '<url>', ws: true, changeOrigin: true }, '/foo': { target: '<other_url>' } } } }
參考:https://github.com/vuejs/vue-cli/tree/dev/docs/zh/config
https://webpack.js.org/configuration/dev-server/