vue axios 跨域代理多個域名 和 網站 basic auth 身份認證


 問題一:用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('請求失敗')
            })
        },

問題解決!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM