問題:在前后端分離的跨域請求中,報跨域問題
配置:
vue.config.js:
module.exports = { devServer: { port: 20110, // 端口號,如果端口號被占用,會自動提升1 host: "localhost", //主機名, 127.0.0.1, 真機 0.0.0.0 https: true, //協議 open: true, //啟動服務時自動打開瀏覽器訪問 proxy: { '/hzhxapi': { target: 'http://www.chengfeiting.com:20089', changeOrigin: true, pathRewrite: { '^/hzhxapi': '' } }, '/wixapi': { target: 'https://www.iocpleasing.com', changeOrigin: true, pathRewrite: { '^/wixapi': '' } } } }, lintOnSave: false, // 關閉格式檢查 productionSourceMap: false, // 打包時不會生成 .map 文件,加快打包速度 }
其中proxy設置了兩個代理,一個代理hzhxapi,另外一個為/wixapi的代理,然后設置對應axios配置
import axios from 'axios' const ts_url = '/hzhxapi'; const iocp_url = '/wixapi'; //axios.defaults.baseURL = iocp_url; axios.defaults.cache = false; const hx_request = axios.create({ baseURL: ts_url, timeout: 100000 }); const wix_request = axios.create({ baseURL: iocp_url, timeout: 100000 }) hx_request.cache = false; iocp_request.cache = false; wix_request.get('/_functions/ProjectList/991010') .then(res => { console.log(res.data) }) .catch(err => { console.error(err); }); hx_request.get('/static/1.json') .then(res => { console.log(res.data) }) .catch(err => { console.error(err); });
然后使用npm run serve,
然后使用谷歌瀏覽器查看獲取數據正確