問題一:用vue +axios 跨域訪問多個不同的域
解決方法:
在 vue.config.js 文件中 devServer中添加
devServer: { proxy: { '^/api/': { target: 'https://www.sougou.com/', ws: true, // proxy websockets changeOrigin: true, //允許跨域 pathRewrite: { '^/api/': '/' // rewrite path } }, '^/api2/': { target: 'https://www.baidu.com/', ws: true, // proxy websockets changeOrigin: true, //允許跨域 pathRewrite: { '^/api2/': '/' // rewrite path } }, } }
附上:測試代碼
test2 () { console.log('test2') axios.get('/api/').then((response) => { if (response.data) { console.log(response.data) } }).catch(err => { alert('請求失敗') }) }, test3 () { console.log('test3') axios.get('/api2/').then((response) => { if (response.data) { console.log(response.data) } }).catch(err => { alert('請求失敗') })
請求結果如下:
問題二:網站的 身份認證 basic auth
解決方法:在get時請求,加一個auth 認證
{ auth: { username: 'admin', password: 'admin' } }
示例:
test () { console.log('test') axios.get('/api/v1/cluster', { auth: { username: 'admin', password: 'admin' } }).then((response) => { if (response.data) { console.log(response.data) } }).catch(err => { alert('請求失敗') }) },
問題解決!!!