開發環境的地址和接口的地址不一樣,會產生跨域問題。
設置代理
在vue.js項目中可以這么設置。
vue.config.js
devServer: { port: 3000, proxy: { '/api': { target:'http://192.168.18.abc', // 代理地址 ws: false, changeOrigin: true, pathRewrite: { '^/api': '' } } } },
假設當前本地的地址是 192.168.18.50:3000,若要獲取某個列表
設置代理之后,訪問本地的項目地址
瀏覽器會先訪問 192.168.18.50:3000/api/xx?xx=yy
代理到這個地址——》https:192.168.18.abc./api/xx?xx=yy
開發環境和生產環境的請求地址是不一樣的,配置打包時的請求地址:
// vue.config.js
module.exports = { publicPath: process.env.NODE_ENV === 'production' ? '/線上地址' : '/' }