使用Axios进行数据请求的时候可能会遇到跨域问题,如下。
我们可以通过Vue的proxy来解决跨域的问题。
Vue2.x中在根目录下的config文件夹中index.js文件中dev对象里proxyTable属性进行相应设置即可解决跨域问题,这里不做详细介绍。
Vue3.0中已经没有config文件夹了,所以需要在根目录新建vue.config.js文件
man.js Vue中挂载一下axios
import { createApp } from 'vue'
import axios from 'axios';
import App from './App.vue'
const app = createApp(App)
app.config.globalProperties.$http = axios;
//Vue3.0中不支持Vue.prototype的方式来挂载axios了,改用上面的方法挂载
app.mount('#app')
在新建的vue.config.js文件中写入如下代码
module.exports = {
publicPath:'./',//静态资源包打包为相对路径
outputDir:'dist',//输出文件
devServer:{
open:false,
host:'0.0.0.0',
port:9090,
hot:true,
proxy: {
'/api': {
target:'http://api.wpbom.com', // 你请求的第三方接口
changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite:{ // 路径重写,
'^/Api': '' // 替换target中的请求地址,也就是说以后你在请求http://api.wpbom.com这个地址的时候直接写成/Api即可。
}
}
},
}
}
假如请求的接口地址为 http://api.wpbom.com/api/neran.php ,在调用接口的地方写入如下代码
//----------指定了pathRewrite时------------------//
export default {
name: 'HelloWorld',
props: {},
mounted(){
this.$http({
method:'get',
url:'Api/api/neran.php',//Api就是proxy中的target地址
data:{}
}).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
}
//-----------未指定PathRewrte时------------------//
export default {
name: 'HelloWorld',
props: {},
mounted(){
this.$http({
method:'get',
url:'/api/neran.php',//没指定BaseUrl路径重写就不需要写了,直接写接口地址就行了。
data:{}
}).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
}
vue.config.js 文件中proxy对象中的pathRewrite属性可写可不写,区别就是在接口调用时要写上重写路径和不需要写上重写路径。