1.前端解决方式
在vue自带的config中的index.js中找到proxyTable:{},在花括号内写如下代码。
'/': {
target: 'http://localhost:8888/', //目标地址
changeOrigin: true, //改变源
pathRewrite: {
'^/': 'http://localhost:8888/' //路径重写
}
}
完整的代码就是proxyTable:{
'/': {
target: 'http://localhost:8888/', //目标地址
changeOrigin: true, //改变源
pathRewrite: {
'^/': 'http://localhost:8888/' //路径重写
}
}
},
上述代码路径重写的意思就是使用http://localhost:8888/来代替“/”,也就是说每次我们请求后端接口时,访问路径“/”就是访问http://localhost:8888/,所以使用axios请求后端接口时这样写
this.$axios(
{
method: 'post',
url: '/login',
params: this.loginForm})
上述代码url:‘/login’可以拆分为两部分,"/"和"login",而"/"又代表http://localhost:8888/,所以这就相当于访问http://localhost:8888/login。
2.java端解决跨域
写一个配置类:
public class CorsConfig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}