解決axios跨域問題


方法一:

一、創建vue項目(vue init webpack projectName)

二、安裝axios(npm insatll axios)

三、配置代理(config/index.js):

在開發環境的代理列表proxyTable添加

'/api': {
        target: 'http://127.0.0.1:8888', //自己服務的ip和服務的端口
        changeOrigin: true,
        pathRewrite: {
          '^/api': 'http://127.0.0.1:8888' //重寫
        }
      }

配置axios的攔截文件config.js(src/api/config.js自己創建)

import axios from 'axios'


/**
 * axios 處理並發請求的助手函數
 */
axios.defaults.baseURL = '/api'

axios.interceptors.request.use(
  config => {
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
axios.interceptors.response.use(function (response) {
  //可以寫判斷獲得的數據返回碼
  return response
}, function (error) {
  return Promise.reject(error)
})
// 請求超時時間
axios.defaults.timeout = 60000

export default axios

四、編寫獲取數據api(src/api/WasteBookAPI.js)

import ajax from './config'


const getAllWithdrawList = function () {
  return new Promise((resove,reject) =>{
    ajax.get('/wastebook/getAllWithdrawList').then(response =>{
      resove(response.data.data)
    }).catch(desc =>{
      reject(desc.data.data)
    })
  })
}

export default {
  getAllWithdrawList
}

五、編寫顯示頁面(調用WasteBookAPI.js內的getAllWithdrawList方法)

六、測試:

方法二:

Spring Boot項目直接使用注解@CrossOrigin,只能給單個controller解決問題,每個controller類都需要添加才行。

方法三:

在服務項目內添加配置文件

/**
 * 實現基本的跨域請求
 * @author hxb
 *
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*是否允許請求帶有驗證信息*/
        corsConfiguration.setAllowCredentials(true);
        /*允許訪問的客戶端域名*/
        corsConfiguration.addAllowedOrigin("*");
        /*允許服務端訪問的客戶端請求頭*/
        corsConfiguration.addAllowedHeader("*");
        /*允許訪問的方法名,GET POST等*/
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

方法四:

Jsonp(還不會使用僅了解)


免責聲明!

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



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