SpringCloud之解决在Vue-cli3.0中Vue-resources和axios的跨域访问问题
1.1、配置cors配置信息,如果使用的是zuul网关路由,需要在zuul网关路由配置 cors配置信息
package com.bean.springcloudzuul.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class GetWayCorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
.allowCredentials(true).maxAge(3600);
}
}
1.2、在Vue-cli配置反向代理,在vue.config.js配置文件中加入
devServer: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8905', //代理接口
changeOrigin: true,
pathRewrite: {
'^/api': '' //代理的路径
}
}
}
}
1.3、在vue-cli3.0的main.js配置axios的跨域访问
import Vue from 'vue'
import App from './App'
import router from './router/router'
import axios from 'axios'
import $ from 'jquery'
import './assets/bootstrap-3.3.7-dist/js/bootstrap.min'
//引入Vuex的store.js文件
import store from './store/store'
import qs from 'qs'
Vue.prototype.axios = axios;
axios.defaults.timeout = 5000;
axios.defaults.withCredentials = true;
1.4、这样你的跨域请求就能够响应成功,如果需要携带session 需要配置全局的session同步,可以使用spring-session-data-redis