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

Angular 18请求报错:GET https://localhost:5001/api/users 连接被拒绝

问题解决步骤

1. 修正请求URL的端口与协议

你代码里请求的是https://localhost:5001/api/users,但实际服务器运行在http://localhost:5245/,端口和协议都不匹配,这是核心问题。把请求地址改成正确的:

this.http.get('http://localhost:5245/api/users').subscribe({
  next: response => this.users = response,
  error: error => console.log(error),
  complete: () => console.log("Request has completed")
})

2. 配置服务器端跨域规则

即使端口改对了,Angular客户端(4200端口)请求5245端口属于跨域请求,若服务器未配置CORS,仍会触发status 0的错误。根据服务器类型添加对应配置:

  • ASP.NET Core:在Program.cs中添加CORS策略
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAngular",
            policy => policy.WithOrigins("http://localhost:4200")
                            .AllowAnyHeader()
                            .AllowAnyMethod());
    });
    app.UseCors("AllowAngular");
    
  • Node.js/Express:使用cors中间件
    const cors = require('cors');
    app.use(cors({ origin: 'http://localhost:4200' }));
    

3. 验证服务器端点可用性

直接在浏览器地址栏或Postman中访问http://localhost:5245/api/users,确认接口能正常返回数据。如果访问失败,优先排查服务器的路由配置和运行状态。

4. 查看浏览器详细错误信息

打开浏览器开发者工具(F12),切换到Network标签:

  • 查看失败请求的Response标签,确认是否有服务器返回的具体错误
  • 检查Console标签的CORS相关报错,快速定位跨域或地址问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 18:04:52