Vue设置
1、在项目根目录创建文件vue.config.js
module.exports = {devServer: {proxy: {'/api': {target: 'http://zlf.plus', //对应自己的接口changeOrigin: true,ws: true,pathRewrite: {'^/api': ''}}}}}
2、 在main.js中配置
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.config.productionTip = falseVue.prototype.$axios = axios
//配置跨域的 `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL
axios.defaults.baseURL = '/api' //关键代码Vue.use(ElementUI);
new Vue({router,render: h => h(App)
}).$mount('#app')
或者使用后端跨域
springBoot配置
1、局部跨域
@RestController
public class TestController {/*** @CrossOrigin 跨域* value:请求的来源的域* maxAge:表示探测请求的有效期* allowedHeaders:表示允许的请求头,*表示所有的请求头都被允许* @return*/@PostMapping("/get")@CrossOrigin(value = "http://localhost:8080",maxAge = 1800,allowedHeaders = "*")public Book getBook(){Book book = new Book();book.setId(100);book.setAuthor("吴承恩");book.setName("西游记");return book;}
}
2、全局配置
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedHeaders("*").allowedMethods("*").maxAge(1800).allowedOrigins("http://localhost:8080");}
}
#案例
<template><div><h1>主页</h1>{{data}} </div>
</template><script>
export default {name:'home',data() {return {data:''}},created() {this.getPost();},methods: {getPost(){this.$axios.request({url:"http://localhost:9090/get", method: 'post'}).then((response)=>{console.log(response.data)this.data = response.data})}},
}
</script><style></style>