日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

axios实现跨域三种方法_跨域的解决方案

發布時間:2023/12/24 综合教程 21 生活家
生活随笔 收集整理的這篇文章主要介紹了 axios实现跨域三种方法_跨域的解决方案 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題背景

Axios是不允許跨域訪問的,別說跨域,跨端口都不行。例如某項目我本地vue前端frontEnd為localhost:8889,Java后臺 backEnd為localhost:8888

報錯信息: Access to XMLHttpRequest at 'http://localhost:8888/cert/certCompany/list2' from origin 'http://localhost:8889' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

axios請求代碼

axios.post('http://localhost:8888/cert/certCompany/list2',JSON.stringify(this.searchParam))
	  .then(function (response) { 
   
	    console.log(response.data);
	  })
	  .catch(function (error) { 
   
	    console.log(error);
	  });

這個時候就有兩個方案了:

  • 修改frontEnd前端,支持跨域(通過代理的形式,當然這種是偽跨域,但是挺有用,前提是后端不限制即可)。
  • 修改backEnd后臺,支持跨域(同時限制可跨域名,不在本文討論范圍,且看過往處理方式):
    SpringBoot之跨域過濾器配置允許跨域訪問
    SpringCloudApiGateway之支持Cors跨域請求

解決方案

main.js

引入axios

//引入axios by zhengkai.blog.csdn.net
import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'  //自動附加在所有axios請求前面,則可以省略/api,直接寫'/xxxx/xxx'。否則需要設置'/api/xxxx/xxx'
config.index.js

改造proxyTable部分,引入虛擬代理 ,請求target這個地址的時候直接寫成/api即可。

dev: { 
   
    env: require('./dev.env'),
    port: 8889,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: { 
   
       //axios跨域改造 by zhengkai.blog.csdn.net
      '/api': { 
   
        target:'http://localhost:8888/cert/', // 你請求的第三方接口
        changeOrigin:true, // 在本地會創建一個虛擬服務端,然后發送請求的數據,并同時接收請求的數據,這樣服務端和服務端進行數據的交互就不會有跨域問題
        pathRewrite:{ 
     // 路徑重寫,
          '^/api': ''  // 替換target中的請求地址,也就是說/api=/target,請求target這個地址的時候直接寫成/api即可。
        }
      }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
業務.vue

修改請求為/api封裝開頭(但是如果你的借口包含/api的關鍵字的話,建議使用其他關鍵字)

//axios跨域請求改造 by zhengkai.blog.csdn.net
axios.post('/certCompany/list2',JSON.stringify(this.searchParam))
      .then(function (response) { 
   
        console.log(response);
      })
      .catch(function (error) { 
   
        console.log(error);
      });

驗證效果

請求不報錯,沒有煩人的No 'Access-Control-Allow-Origin' header is present on the requested resource.報錯。

總結

以上是生活随笔為你收集整理的axios实现跨域三种方法_跨域的解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。