Spring Boot与Angular跨域(CORS)问题求助:本地后端对接StackBlitz失败
解决StackBlitz Angular对接本地Spring Boot的请求Pending/Net::Error问题
核心问题原因
- StackBlitz无法访问本地localhost:StackBlitz运行在云端Web容器中,其环境内的
localhost指向容器自身,而非你的本地机器,直接请求http://localhost:8080会因无法连接而处于pending状态。 - CORS配置未生效:原Spring Boot的CORS配置仅添加了路径映射,但未明确指定允许的跨域源,实际未开启有效跨域支持。
- 本地代理配置无效:Angular的
proxy.conf.json仅对本地运行的Angular项目生效,StackBlitz无法读取你本地的代理配置,因此代理规则不生效。
解决方案步骤
1. 暴露本地Spring Boot服务到公网
使用隧道工具(如ngrok)将本地8080端口映射到公网:
- 下载并安装ngrok
- 终端运行命令:
ngrok http 8080
- 执行后会生成一个公网HTTPS地址(如
https://xxxx-xx-xx-xx-xx.ngrok.io),复制该地址备用。
2. 修正Spring Boot的CORS配置
修改WebConfig,明确允许StackBlitz的域名和ngrok公网地址:
@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 替换为你的StackBlitz地址和ngrok地址 .allowedOrigins( "https://stackblitzstartersf3qupm-d2jk--4200--dc4d7514.local-credentialless.webcontainer.io", "https://xxxx-xx-xx-xx-xx.ngrok.io" ) .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true); } }
重启Spring Boot服务使配置生效。
3. 调整Angular服务的请求地址
将HelloService中的本地地址替换为ngrok生成的公网地址:
export class HelloService { private apiURL = 'https://xxxx-xx-xx-xx-xx.ngrok.io'; // 替换为你的ngrok公网地址 constructor(private http: HttpClient) {} getGreetings(): Observable<string> { return this.http.get<string>(`${this.apiURL}`); } }
验证
- 确保ngrok保持运行状态,Spring Boot服务重启完成。
- 在StackBlitz中重新运行Angular应用,查看控制台和网络面板,请求应能正常返回数据。
内容的提问来源于stack exchange,提问作者nino144
相关产品推荐
相关产品推荐

