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

Angular14调用第三方API遇CORS及凭证空值错误的解决方法

解决Angular 14中第三方API调用的CORS、请求失败及凭证为空问题

错误分析与分步解决

1. 凭证为空错误(Caller credential cannot be empty)

该错误源于自定义请求头未正确传递给第三方API,需确保secId、secName、secPassword三个凭证字段被正确加入HTTP请求头。

2. CORS跨域错误

浏览器同源策略禁止前端直接请求未配置CORS的第三方API,需通过Angular代理将请求转发,规避跨域限制。

3. Http请求失败错误

此错误为前两个问题引发的连锁反应,解决凭证传递和跨域问题后,请求失败问题会自动修复。


完整实现代码

1. API服务(account.service.ts)

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, catchError } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class AccountService {
  // 用代理路径替代直接的第三方API地址
  private apiUrl = '/api/AccountDetail';

  // 构建凭证请求头
  private getAuthHeaders(): HttpHeaders {
    return new HttpHeaders({
      'secId': 'knt10',
      'secName': 'kkcm',
      'secPassword': 'nnkml'
    });
  }

  constructor(private http: HttpClient) { }

  getAccountDetail(accountNumber: string): Observable<any> {
    const params = new HttpParams().set('accountNumber', accountNumber);
    return this.http.get(this.apiUrl, {
      headers: this.getAuthHeaders(),
      params: params
    }).pipe(
      catchError(err => {
        console.error('API请求错误:', err);
        throw err;
      })
    );
  }
}

2. 组件逻辑(account.component.ts)

import { Component } from '@angular/core';
import { AccountService } from './account.service';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent {
  accountNumber = '';
  customerName: string | null = null;
  errorMessage = '';

  constructor(private accountService: AccountService) { }

  onAccountInputChange(): void {
    this.customerName = null;
    this.errorMessage = '';
    // 仅输入10位账号时发起请求
    if (this.accountNumber.length === 10) {
      this.accountService.getAccountDetail(this.accountNumber).subscribe({
        next: (response) => {
          this.customerName = response.CustomerName;
        },
        error: (err) => {
          this.errorMessage = '获取客户信息失败,请检查账号或稍后重试';
        }
      });
    }
  }
}

3. 组件模板(account.component.html)

<div class="account-container">
  <label for="accountNumber">账号:</label>
  <input
    id="accountNumber"
    type="text"
    [(ngModel)]="accountNumber"
    (input)="onAccountInputChange()"
    placeholder="请输入10位账号"
    maxlength="10"
  >
  <div *ngIf="customerName" class="customer-name">客户名:{{ customerName }}</div>
  <div *ngIf="errorMessage" class="error-message">{{ errorMessage }}</div>
</div>

配置Angular代理解决CORS问题

  1. 项目根目录创建proxy.conf.json文件:
{
  "/api/*": {
    "target": "https://thirtpartyapi.com",
    "secure": true,
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    }
  }
}
  1. 修改angular.json的serve配置,添加代理路径:
"projects": {
  "your-project-name": {
    "architect": {
      "serve": {
        "options": {
          "proxyConfig": "proxy.conf.json"
        }
      }
    }
  }
}
  1. 重启开发服务器:
ng serve --proxy-config proxy.conf.json

验证要点

  • 输入10位账号后,通过浏览器开发者工具的Network标签,确认请求头已携带三个凭证字段,且请求通过代理转发至第三方API。
  • 若仍有问题,检查代理配置是否正确,或第三方API的参数格式是否匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:24:21