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

Angular13项目Cross-Origin Request Blocked跨域问题求助

解决Angular跨域请求错误的方案

核心问题分析

你遇到的CORS错误,本质是前端错误地在请求里携带了Access-Control-*系列响应头——这类头是后端服务器返回给浏览器用来允许跨域的,不是前端发起请求时该带的。另外你的代码还有语法错误('Access-Control-Allow-Headers': 'Content-Type,这行引号没闭合),这也会导致请求异常。

步骤1:修正前端Service代码

把请求里多余的CORS头删掉,只保留必要的请求配置:

import { Inject, Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { APP_CONFIG, IAppConfig } from '../club/core/app.config';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class NewsService {

  constructor(@Inject(APP_CONFIG) private appConfig: IAppConfig, private http: HttpClient) { }

  GetPersonLevel(){
    // 只设置必要的请求头,比如如果接口需要Content-Type的话
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    // observe: response 是请求配置项,不属于请求头,需单独配置
    return this.http.get('https://X.com/club/v1/vPersonLevelService/vPersonLevelDashboard', {
      headers: headers,
      observe: 'response'
    }).pipe(map((res: any) => res));
  }

}

步骤2:后端Java/Tomcat配置CORS

方式1:接口级注解(Spring Boot项目)

在对应的Controller方法或类上添加@CrossOrigin注解,精准控制跨域权限:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
// 允许前端localhost地址跨域,指定允许的请求头
@CrossOrigin(origins = "http://localhost:4200", allowedHeaders = "Content-Type")
public class PersonLevelController {
    @GetMapping("/club/v1/vPersonLevelService/vPersonLevelDashboard")
    public Object getPersonLevel() {
        // 业务逻辑实现
        return result;
    }
}

方式2:全局CORS过滤器(Spring Boot项目)

创建全局过滤器,统一处理所有请求的跨域规则:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 指定允许的前端来源,避免用*(若请求带Cookie则必须指定具体地址)
        config.addAllowedOrigin("http://localhost:4200");
        // 允许的请求头
        config.addAllowedHeader("Content-Type");
        // 允许的请求方法
        config.addAllowedMethod("*");
        // 允许携带Cookie(按需开启)
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

纯Tomcat项目配置

在web.xml中添加CORS过滤器:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>http://localhost:4200</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,PUT,DELETE,OPTIONS</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

步骤3:Nginx层面配置(若用Nginx反向代理)

如果API通过Nginx转发,可在location块中添加跨域规则:

location /club/ {
    # 允许前端localhost地址
    add_header Access-Control-Allow-Origin http://localhost:4200;
    # 允许的请求方法
    add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
    # 允许的请求头
    add_header Access-Control-Allow-Headers Content-Type;
    # 允许携带Cookie(按需开启)
    add_header Access-Control-Allow-Credentials true;

    # 处理OPTIONS预请求,直接返回204
    if ($request_method = OPTIONS) {
        return 204;
    }

    # 转发到后端Tomcat服务
    proxy_pass http://your-tomcat-address:8080;
}

关键注意点

  • 绝对不要在前端请求中添加Access-Control-*头,这类头是后端返回给浏览器的响应头,前端添加会触发预请求检查失败。
  • 尽量避免用*作为允许的来源,指定具体前端地址更安全;若请求需携带Cookie,必须明确指定来源,不能用*。
  • 确保后端正确处理OPTIONS预请求,浏览器会在发送实际请求前先发送OPTIONS请求验证跨域权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:08:12