前后端跨域问题解决
1.从前端解决;
以vue为例,可以vite.config.js/ts来修改
export default defineConfig({server: {proxy: {'/api': 'http://localhost:8123',}},
})
然后我们使用的时候就可以直接移除请求前缀来使用了
// 创建 Axios 实例
const myAxios = axios.create({baseURL: '',timeout: 60000,withCredentials: true,
})
2.通过后端解决
通过配置全局跨域,通过@configuration
/*** 全局跨域配置*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {// 覆盖所有请求registry.addMapping("/**")// 允许发送 Cookie.allowCredentials(true)// 放行哪些域名(必须用 patterns,否则 * 会和 allowCredentials 冲突).allowedOriginPatterns("*").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedHeaders("*").exposedHeaders("*");}
}
