如何配置SpringBoot,允许localhost与10.0.2.2的请求访问
配置SpringBoot同时支持localhost和10.0.2.2访问
1. 确保应用绑定所有网络接口
SpringBoot默认绑定地址为0.0.0.0,已支持从任意IP访问。若曾修改过绑定地址,需在配置文件中恢复:
- 在
application.properties添加:server.address=0.0.0.0 - 或在
application.yml添加:server: address: 0.0.0.0
2. 配置CORS(跨域资源共享)
由于Angular前端与后端存在跨域场景,需明确允许指定来源的请求:
方法一:全局CORS配置类
创建配置类实现全局跨域规则:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:4200", "http://10.0.2.2:4200") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true); } }; } }
注意替换4200为你的Angular实际端口。
方法二:配置文件直接设置(SpringBoot 2.4+支持)
在application.properties中添加:
spring.web.cors.allowed-origins=http://localhost:4200,http://10.0.2.2:4200 spring.web.cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS spring.web.cors.allowed-headers=* spring.web.cors.allow-credentials=true
或application.yml:
spring: web: cors: allowed-origins: - "http://localhost:4200" - "http://10.0.2.2:4200" allowed-methods: "*" allowed-headers: "*" allow-credentials: true
3. Spring Security适配配置(若集成安全框架)
如果项目使用Spring Security,需在安全配置中放行跨域请求及OPTIONS预检请求:
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import java.util.List; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() .authorizeRequests() // 按需添加权限规则 .anyRequest().permitAll(); } @Override protected CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("http://localhost:4200", "http://10.0.2.2:4200")); config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(List.of("*")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } }
验证配置
启动SpringBoot应用后,分别从Angular的localhost:4200和10.0.2.2:4200发起请求,确认后端正常响应且无跨域报错。
内容的提问来源于stack exchange,提问作者fnyve
相关产品推荐
相关产品推荐

