SpringBoot与VueCLI解决跨域问题
前端Vue配置
// vue.config.js
module.exports = {
devServer : {
proxy: {
// /api下的所有的请求全被代理了
'/api': {
target: 'http://192.168.238.128:8081', // 服务端地址
ws: true,
changeOrigin: true,
pathRewrite: { // 路径重写看情况,如果后端接口路径有/api/则不需要设置
'^/api': ""
}
}
}
}
}
Java后端设置
只需在实现了WebMvcConfigurer接口的实现类中,实现addCorsMappings方法就行
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") // 该方法才能全匹配,allowedOrigins()需要精确匹配
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}