问题描述
Vue开发的时候,由于本地的浏览器环境是http://localhost:8080类似这样的地址,而API地址,很可能是后端开发的,不在同一台而AXIOS导致跨域无法请求的问题。
解决
可以利用vue的代理功能,让vue使用proxy去转发流量给API服务器,从而避免跨域问题
假设API服务器的API链接都是/api开头的,如果是开发环境,baseURL就设置为api,是相对路径,这样根据下面的vue.config.js的配置,匹配规则的都转发给proxy服务器
http.js
import axios from 'axios'
export const WEB_BASE = 'http://192.168.21.11';
// axios 配置
const isProduction = Object.is(process.env.NODE_ENV, 'production');
// console.log("isProduction: "+isProduction);
axios.defaults.timeout = 20000;
// 假设API服务器的API链接都是/api开头的,如果是开发环境,baseURL就设置为api,是相对路径,这样根据下面的vue.config.js的配置,匹配规则的都转发给proxy服务器
axios.defaults.baseURL = isProduction ? WEB_BASE + '/api/' : 'api/'; //这是调用数据接口
vue.config.js
module.exports = {
publicPath: '',
css: {
loaderOptions: {
less: {
javascriptEnabled: true,
}
}
},
//see https://cli.vuejs.org/zh/config/#devserver
// devServer: {
// proxy: 'http://localhost:8182'
// },
devServer: {
proxy: {
'/api': {
target: 'http://192.168.21.11',
changeOrigin: true,
//secure: false, // 如果是https接口,需要配置这个参数
}
}
},
};
文章评论