You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot与Angular跨域(CORS)问题求助:本地后端对接StackBlitz失败

解决StackBlitz Angular对接本地Spring Boot的请求Pending/Net::Error问题

核心问题原因

  1. StackBlitz无法访问本地localhost:StackBlitz运行在云端Web容器中,其环境内的localhost指向容器自身,而非你的本地机器,直接请求http://localhost:8080会因无法连接而处于pending状态。
  2. CORS配置未生效:原Spring Boot的CORS配置仅添加了路径映射,但未明确指定允许的跨域源,实际未开启有效跨域支持。
  3. 本地代理配置无效: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}`);
    }
}

验证

  1. 确保ngrok保持运行状态,Spring Boot服务重启完成。
  2. 在StackBlitz中重新运行Angular应用,查看控制台和网络面板,请求应能正常返回数据。

内容的提问来源于stack exchange,提问作者nino144

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 04:22:40