go、spring boot、vert.x 用CORS解決跨域
阿新 • • 發佈:2018-12-29
go gin 使用github.com/gin-contrib/cors
package main import "github.com/gin-gonic/gin" import "github.com/gin-contrib/cors" func main() { r := gin.Default() //cors r.Use(cors.New(cors.Config{ AllowOrigins: []string{"*"}, AllowMethods: []string{"PUT", "PATCH", "GET", "POST", "DELETE"}, AllowHeaders: []string{"content-type"}, ExposeHeaders: []string{"X-Total-Count"}, })) r.GET("/test", func(c *gin.Context) { c.JSON(200, gin.H{ "test": success, }) }) r.Run() // listen on 0.0.0.0:8080 }
Spring Boot 使用配置類
@Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setAllowCredentials(true); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } @Bean public MultipartResolver multipartResolver() { return new CommonsMultipartResolver(); } }
Vert.x 使用 CorsHandler
//cors
router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.POST));