方法1:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * @Description 全局跨域处理(测试环境或生产环境nginx配置跨域后, 服务端不应再设置跨域, 否则会出现两次跨域设置, 跨域不生效问题) * @Author lc * @Date 2019/6/26 0026 下午 3:07 **/ @Configuration public class WebConfig extends WebMvcConfigurerAdapter { /** * @return void * @Description 配置全局跨域处理 * @Author lc * @Date 2019/6/26 0026 下午 3:10 * @Param [registry] **/ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .maxAge(3600) .allowCredentials(true); } }
方法二:
import com.fendan.manager.dto.Result;
import io.swagger.annotations.ApiOperation; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import javax.servlet.http.HttpServletResponse; /** * @Description //TODO * @Author lc * @Date 2019/6/26 0026 下午 3:24 **/ public class TestController { @ApiOperation("跨域测试") @PostMapping(value = "/test") @Validated public Result test(HttpServletResponse response) { // 响应头设置 response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept"); // 指定允许其他域名访问 response.addHeader("Access-Control-Allow-Origin", "*"); // 响应类型 response.addHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE"); // 最大值设置 response.addHeader("Access-Control-Max-Age", "1000"); return null; } }