// axios 中的GET請求 axios.get('/user', { params: { ID: ‘001’ } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // axios 中的POST請求 axios.post('/user', { firstName: '1', lastName: '2' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
方案1:既然使用axios直接進行跨域訪問不可行,咱們就須要配置代理了。代理能夠解決的緣由:由於客戶端請求服務端的數據是存在跨域問題的,而服務器和服務器之間能夠相互請求數據,是沒有跨域的概念(若是服務器沒有設置禁止跨域的權限問題),也就是說,咱們能夠配置一個代理的服務器能夠請求另外一個服務器中的數據,而後把請求出來的數據返回到咱們的代理服務器中,代理服務器再返回數據給咱們的客戶端,這樣咱們就能夠實現跨域訪問數據。php
準備工做:安裝所需中間件和插件等,好比axios,http-proxy-middleware等。css
具體案例:這裏以訪問豆瓣Top250爲例,直接訪問以下:前端
axios.get("http://api.douban.com/v2/movie/top250")
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})vue
當執行npm run dev時,控制檯報錯以下:webpack
事實證實直接請求確實出現跨域問題了,下面具體演示解決跨域問題的步驟:ios
上面所說的必備條件都已安裝完成的狀況下,執行如下步驟便可解決問題:git
1.配置BaseUrlgithub
在main.js中,配置數據所在服務器的前綴(即固定部分),代碼以下:web
// 項目入口,配置全局vue import Vue from 'vue' import VueRouter from './router/routes.js' import Store from './store/index.js' import './assets/less/index.less' import App from './App.vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-default/index.css' import axios from 'axios' Vue.prototype.$axios = axios axios.defaults.baseURL = '/api' //關鍵代碼 Vue.config.productionTip = false Vue.use(ElementUI); new Vue({ router:VueRouter, store:Store, template:'<App/>', components: {App} }).$mount('#app') // 默認進入商品模塊 // VueRouter.push({ path: '/home' })
關鍵代碼:axios.defaults.baseURL = '/api',做用是咱們每次發送的請求都會帶一個/api的前綴。npm
2.配置代理
在config文件夾下的index.js文件中的proxyTable字段中,做以下處理:
dev: { env: require('./dev.env'), port: 8090, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target:'http://api.douban.com/v2', // 你請求的第三方接口 changeOrigin:true, // 在本地會建立一個虛擬服務端,而後發送請求的數據,並同時接收請求的數據,這樣服務端和服務端進行數據的交互就不會有跨域問題 pathRewrite:{ // 路徑重寫, '^/api': '' // 替換target中的請求地址,也就是說之後你在請求http://api.douban.com/v2/XXXXX這個地址的時候直接寫成/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 }
3.在具體使用axios的地方,修改url以下便可:
axios.get("/movie/top250").then((res) => { res = res.data if (res.errno === ERR_OK) { this.themeList=res.data; } }).catch((error) => { console.warn(error) })
4.從新啓動項目以後,已經解決了跨域問題,結果以下:
【注意】:必須重啓項目!!
原理:
由於咱們給url加上了前綴/api,咱們訪問/movie/top250就當於訪問了:localhost:8080/api/movie/top250(其中localhost:8080是默認的IP和端口)。
在index.js中的proxyTable中攔截了/api,並把/api及其前面的全部替換成了target中的內容,所以實際訪問Url是http://api.douban.com/v2/movie/top250。
至此,純前端配置代理解決axios跨域獲得解決。
根據評論區內容,區分一下生產環境和開發環境,集體配置以下:
1.在config文件夾裏面建立一個api.config.js的配置文件
const isPro = Object.is(process.env.NODE_ENV, 'production')
console.log(isPro);
module.exports = {
baseUrl: isPro ? 'https://www.***/index.php/Official(線上地址)' : 'api/'
}
2.在main.js文件裏面引入上面文件,這樣就能夠保證動態的匹配生產和開發環境的定義前綴了,代碼以下:
import Vue from 'vue'
import App from './App'
import router from './router'
import 'bootstrap/dist/js/bootstrap.min'
import 'bootstrap/dist/css/bootstrap.min.css'
import axios from 'axios'
import apiConfig from '../config/api.config'
Vue.prototype.$axios = axios;
Vue.config.productionTip = false;
axios.defaults.baseURL = apiConfig.baseUrl;// 配置接口地址
axios.defaults.withCredentials = false;
以上兩步便可解決vue的跨域問題,而且能夠能夠直接build打包到線上,若有問題,請評論區留言,但願對你有所幫助。
點贊 20