使用前后端分离的时候,会产生的跨域问题。
而根据项目的创建会生成不同的vue项目结构
使用webpack创建:配置在vue.config.js下
使用脚手架vue-cli :配置在config文件夹下
例如我需要获取的数据地址:
http://106.14.92.224:9097/api/client/covid19
一、vue中有config文件夹时
1、在config文件夹下面的index.js添加
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
//代理请求路径
proxyTable: {
'/api':{
//修改为数据请求的前缀
target:"http://106.14.92.224:9097",
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}
},
....
}
2、在main.js里面,设置全局和路由基本路径
//引入axios
import Axios from 'axios'
import axios from 'axios';
Vue.prototype.$ajax = axios
// 设置全局的axios
Vue.prototype.$axios=Axios
// 设置基本路径
Axios.defaults.baseURL='/api'
3、在需要获取数据的页面调用
this.$axios.get('/api/client/covid19’).then(res => {
console.log(res.data);
}).catch(function (error) {
console.log(error);
});
二、如果是没有config文件夹的vue项目
1、在vue项目的根目录里的vue.config.js添加跨域代理
devServer: {
proxy:{
'/api':{
target: 'http://106.14.92.224:9097',
changeOrigin:true,
pathRewrite: {
'^/api': ''
}
}
}
},
记录vue.config.js可以配置的信息
devServer: {
disableHostCheck: false,
host: "192.168.xx.xx",
port: 8080,
https: false,
hotOnly: false,
proxy: null
},
2、在自己封装的axios方法request.js中设置baseURL
import axios from 'axios'
const instance = axios.create({
baseURL:'/api',
timeout:5000,
})
export function get(url,params){
console.log(url);
return instance.get(url,{params})
}
3、调用
getData(){
// http://localhost:8080/government
let url = '/api/client/covid19'
get(url).then(resp=>{
console.log('resp',resp);
})
},