spring40怎么解决前后端跨域问题
在Spring 4.0中解决前后端跨域问题可以通过以下步骤:
- 添加CORS过滤器
在Spring配置文件中,添加CORS过滤器来允许跨域请求。可以使用以下代码:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
.allowCredentials(false).maxAge(3600);
}
}
- 添加@CrossOrigin注解
在Controller中添加@CrossOrigin注解来允许跨域请求。可以使用以下代码:
@RestController
@RequestMapping("/api")
public class ApiController {
@CrossOrigin(origins = "*")
@RequestMapping("/test")
public String test() {
return "Hello World!";
}
}
- 配置Web安全
在Web安全配置中,添加CORS配置来允许跨域请求。可以使用以下代码:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
.and().csrf().disable();
}
}
以上是Spring 4.0解决前后端跨域问题的几种方式,可以根据实际情况选择适合自己的方法
原文地址: https://www.cveoy.top/t/topic/dW9Y 著作权归作者所有。请勿转载和采集!