在vue-cli生成的项目中,使用axios跨域请求时,会报错,前端解决方案配置如下:
- vue.config.js
module.exports = {
publicPath: './',
devServer: {
open: true, //浏览器自动打开页面
host: "localhost", //如果是真机测试,就使用这个IP
port: 8080,
https: false,
hotOnly: false, //热更新(webpack已实现了,这里false即可)
proxy: {
//配置跨域-将所有/api的请求拦截,代理到target上
'/api': {
target: "http://yangxc.cn:7001/test-api",
ws:true,
changOrigin:true,
pathRewrite:{ //---->>>并将/api换成/
'^/api':'/'
}
}
}
}
}
- main.js
import Vue from 'vue'
import App from './App.vue'
import Axios from 'axios'
// 引入vant
import Vant from 'vant'
import 'vant/lib/index.css'
Vue.use(Vant);
Vue.config.productionTip = false
Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/api' // <<<<<<<------此处将所有经过axios的请求加上了/api
Axios.defaults.headers.post['Content-Type'] = 'application/json';
import router from "./router"
new Vue({
render: h => h(App),
router,
}).$mount('#app')









网友评论