设置,附源码)
后端代码使用springboot框架开发的使用postman测试接口可以正常使用但是接口提供到前端是显示403 Forbidden报错的无法请求。在后端代码中可以进行跨域配置添加一个config文件即可通过Configuration注解来实现importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.CorsRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;ConfigurationpublicclassCorsConfigimplementsWebMvcConfigurer{OverridepublicvoidaddCorsMappings(CorsRegistryregistry){registry.addMapping(/**)// 对所有路径应用CORS配置.allowedOriginPatterns(*).allowedMethods(GET,POST,PUT,DELETE,OPTIONS).allowedHeaders(*).allowCredentials(true);}}方法说明allowedOrigins(String... origins)指定允许的源域名allowedOriginPatterns(String... patterns)推荐指定允许的源模式支持通配符 *Spring Boot 2.4 推荐此方式allowedMethods(String... methods)指定允许的 HTTP 方法例如 “GET”, “POST”, “PUT”, “DELETE”, OPTIONS等allowedHeaders(String... headers)指定实际请求中允许的请求头字段“*” 表示允许所有allowCredentials(boolean allow)是否允许跨域请求携带凭证Cookie、Authorization 等。设为 true 时allowedOrigins 不可为 “*” 。maxAge(long maxAge)预检请求OPTIONS的缓存时间单位秒减少重复预检次数 。