Vue proxyTable配置多個接口地址,解決跨域的問題
最開始的時候,因?yàn)檎埱蠛笈_出現(xiàn)跨域問題。
查找資料配置proxyTable,解決跨域問題。如下圖所示:
axios請求頁面:
this.$axios.post(’/api/weblogin/login’,data).then(res=>{ console.log(res)})
后面遇到需要連接不同的接口域名,我在proxyTable里增加了一個apiGas。axios請求存在獲取得到api但是不能獲取apiGas(提示請求資源不存在)。
proxyTable: { ’/api’: { target: ’http://’, // 接口域名 changeOrigin: true, //是否跨域 pathRewrite: { ’^/api’: ’/bsgzf/api/auth/’ , //需要rewrite的, }, }, ’/apiGas’: { target: ’http://’, // 接口域名 changeOrigin: true, //是否跨域 pathRewrite: { ’^/apiGas’:’/bsgzf/api/gas/’ } }, },
查找了很多資料都沒有具體的解決方法,偶然在一個相同的問題下發(fā)現(xiàn)一個回復(fù),讓把這兩個鏈接位置換一下,抱著試一試的態(tài)度換了,重新運(yùn)行,結(jié)果兩個都可以獲取了。不知道什么原理???有知道的請指教!!!
正解:
proxyTable: { ’/apiGas’: { target: ’http://’, // 接口域名 changeOrigin: true, //是否跨域 pathRewrite: { ’^/apiGas’:’/bsgzf/api/gas/’ } }, ’/api’: { target: ’http://’, // 接口域名 changeOrigin: true, //是否跨域 pathRewrite: { ’^/api’: ’/bsgzf/api/auth/’ , //需要rewrite的, }, }, },
補(bǔ)充知識:Vue里的proxyTable解決跨域,api接口管理
本文單純的介紹Vue項(xiàng)目中接口的集中管理以及跨域的解決方法。
1.webpack里的proxyTable設(shè)置跨域:config->index.js
module.exports = { dev: { assetsSubDirectory: ’static’, assetsPublicPath: ’/’, proxyTable: { ’/api’:{ target:’http://localhost:80’, //這里配置的是 請求接口的域名 // secure: false, // 如果是https接口,需要配置這個參數(shù) changeOrigin: true, // 如果接口跨域,需要進(jìn)行這個參數(shù)配置 pathRewrite:{ ’^/api’:’’ //路徑重寫,這里理解成用’/api’代替target里面的地址. } } }, }
2.設(shè)置api
2.1文件目錄
2.2 api.js 編碼
import axios from ’axios’axios.defaults.baseURL = ’/api’;axios.defaults.headers.post[’Content-Type’] = ’application/json;charset=utf-8’;axios.defaults.withCredentials = true//接口自定義//修改用戶信息接口export const updateOneUser = params => { return axios.post(’/anta/anta-back/src/php/updateUser.php’, params) .then(res => res.data)};
3.組件中引用
import {updateOneUser} from '../../api/api'methods:{ //給后臺發(fā)送數(shù)據(jù) var params = new URLSearchParams(); params.append(’userphone’, this.watchStudentInfo.userphone); params.append(’userpass’, this.watchStudentInfo.userpass); console.log(params) updateOneUser(params).then(data=>{ //后臺返回的數(shù)據(jù) if(data==1){ //添加成功 this.$message.success(’修改成功’) }else{ //失敗 this.$message.success(’修改失敗’) } }).catch(error=>{ this.$message.success(’修改失敗’) })}
以上這篇Vue proxyTable配置多個接口地址,解決跨域的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
