Vue跨域Access to XMLHttpRequest at 'http://192.168.1.2:9090/api/bbs/bbs/art/' from origin 'http://l...

跨域提示信息

Access to XMLHttpRequest at 'http://192.168.1.2:9090/api/bbs/bbs/art/' from origin 'http://localhost:8083' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed

跨域提示

什么是跨域

跨域指瀏覽器不允許當(dāng)前頁(yè)面的所在的源去請(qǐng)求另一個(gè)源的數(shù)據(jù)。源指協(xié)議,端口,域名。只要這個(gè)3個(gè)中有一個(gè)不同就是跨域。

  • 這里列舉一個(gè)經(jīng)典的列子:
#協(xié)議跨域
http://a.baidu.com 訪問(wèn) https://a.baidu.com;
#端口跨域
http://a.baidu.com:8080 訪問(wèn)  http://a.baidu.com:80;
#域名跨域
http://a.baidu.com  訪問(wèn)  http://b.baidu.com;

解決跨域方法

  • 1.前提這里是使用vue腳手架生成的標(biāo)準(zhǔn)項(xiàng)目為準(zhǔn)。一般在項(xiàng)目config目錄下面有個(gè)index文件
module.exports = {
    dev: {
        // Paths
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
            '/api': {
                target: 'http://192.168.1.2:9090', //后端接口地址
                changeOrigin: true,  //是否允許跨越
                pathRewrite: {
                    '^/api': '/api',        //重寫,
                }
            }
        },
 host: 'localhost',   //本地ip
 port: 8083,
            ...

后端請(qǐng)求地址是http://192.168.1.2:9090,所有api的接口url都以/api開(kāi)頭。
所以首先需要匹配所有以/api開(kāi)頭的.然后修改target的地址為http://192.168.1.2:9090
最后修改pathRewrite地址:將前綴'^api'轉(zhuǎn)為'/api'。
如果本身的接口地址就有'/api'這種通用前綴,就可以把pathRewrite 刪掉。注意這個(gè)方式只能在開(kāi)發(fā)環(huán)境中使用。

  • 2.在main.js文件,配置一下axios.defaults.baseURL = '/api'這樣就可以保證動(dòng)態(tài)的匹配生產(chǎn)和開(kāi)發(fā)環(huán)境的定義前綴了,代碼如下:
/*
入口JS
*/
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'        //關(guān)鍵代碼
Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

3.組件中axios請(qǐng)求數(shù)據(jù)使用:

<template>
 
</template>

<script>
    import Footer from './components/Footer/Footer.vue'
    export default {
        created() {
            const url = '/api/bbs/bbs/art'
            this.$axios.get(url).then(res => {
                console.log(res)
            })
        },
    }
</script>

4.重新啟動(dòng)項(xiàng)目之后,已經(jīng)解決了跨域問(wèn)題

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容