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

Angular中调用GET接口遇CORS报错但响应含有效数据,如何获取?

Fixing CORS Error with Angular HttpClient (Even When Response is Visible in Network Tab)

Hey Juan, I totally get how confusing this can be—you see the correct response in your browser's network panel, but Angular throws a CORS error and won't let your code access that data. Let's break down why this happens and how to fix it.

Why You See the Response But Get an Error

This is all about the browser's same-origin policy. When your Angular app (running on http://localhost:4200 for example) makes a request to a different domain, the browser:

  1. Sends the request to the target server
  2. Receives the full response back (which is why you can see it in the network tab)
  3. Checks if the server's response includes valid CORS headers (like Access-Control-Allow-Origin that matches your app's origin)
  4. If the headers are missing or invalid, the browser blocks your JavaScript code from accessing the response—even though it already received it.

Solutions to Fix the CORS Issue

1. Configure CORS on the Target Server (Best Practice)

The most reliable fix is to update the backend server to include the necessary CORS headers. This tells the browser that your app is allowed to access the API.

For example:

  • If using Node.js/Express: Install the cors middleware and enable it
    const cors = require('cors');
    app.use(cors({ origin: 'http://localhost:4200' })); // Allow your Angular app's origin
    
  • If using Java Spring: Add the @CrossOrigin annotation to your controller or configure global CORS settings
    @CrossOrigin(origins = "http://localhost:4200")
    @RestController
    public class YourController {
      // ...
    }
    
  • For other backend frameworks, look up how to set Access-Control-Allow-Origin, Access-Control-Allow-Methods, and related headers.

2. Use Angular's Proxy Configuration (Development Only)

If you can't modify the backend server right now (like during development), Angular has a built-in proxy to bypass CORS. Here's how to set it up:

  1. Create a proxy.conf.json file in your Angular project root:
    {
      "/api": {
        "target": "https://your-target-api-domain.com",
        "secure": false,
        "changeOrigin": true,
        "pathRewrite": { "^/api": "" } // Optional: Remove /api prefix from the request sent to the server
      }
    }
    
  2. Update your angular.json to use this proxy when serving the app:
    "architect": {
      "serve": {
        "builder": "@angular-devkit/build-angular:dev-server",
        "options": {
          "proxyConfig": "proxy.conf.json"
        }
      }
    }
    
  3. Modify your HttpClient service to use the proxy path instead of the full API URL:
    // HttpclientmanagerService类
    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders} from '@angular/common/http';
    import { Observable } from "rxjs/Observable";
    
    @Injectable()
    export class HttpclientmanagerService {
      // Use /api instead of the full domain
      private apiUrl = '/api/your-endpoint-path';
    
      constructor(private http: HttpClient) { }
    
      fetchData(): Observable<any> {
        const headers = new HttpHeaders({
          // Add any required headers here
        });
        return this.http.get<any>(this.apiUrl, { headers });
      }
    }
    
  4. Restart your Angular dev server with ng serve—the proxy will forward requests to the target API, and the browser won't throw a CORS error.

3. Use a Backend Proxy (Production Environment)

For production, you can't rely on Angular's dev proxy. Instead, set up a backend service (like a Node.js server or Nginx) to act as a middleman:

  • Your Angular app sends requests to your backend proxy
  • The proxy forwards the request to the target API
  • The proxy adds the necessary CORS headers to the response before sending it back to your app

Important Note

Avoid using browser extensions to bypass CORS—these only work for your local testing and won't fix the issue for real users.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:44:05