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
相关产品推荐
相关产品推荐

