package com.example.springbootdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication public class SpringbootdemoApplication extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(SpringbootdemoApplication.class, args); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowCredentials(true) .allowedHeaders("*") .allowedOrigins("*") .allowedMethods("*"); } }
2、在允許跨域請求的controller中使用@CrossOrigin 注解
import org.springframework.web.bind.annotation.CrossOrigin; @CrossOrigin @RestController public class HelloWorldController { /** * * */ }