報錯: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
就是說跨域問題。
1.使用@CrossOrigin
註解
如果想要對某一接口配置 CORS,可以在方法上添加 @CrossOrigin 註解 :
@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
}
如果想對一系列接口添加 CORS 配置,可以在類上添加註解,對該類聲明所有接口都有效:
@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
}
2.添加配置類
如果想添加全局配置,則需要添加一個配置類 :
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}