解决Angular项目接入Sentry时的CORS错误问题
环境信息
Angular CLI: 13.3.11 Node: 18.16.0 (Unsupported) Package Manager: npm 9.5.1 OS: darwin arm64 Angular: 13.4.0
问题描述
向 Sentry 地址 https://xxxxx.ingest.sentry.io/api/xxxxxxx/envelope/?sentry_key=xxxxxxxx&sentry_version=7&sentry_client=sentry.javascript.angular-ivy%2F7.66.0 发送 POST 请求时,收到响应:
{"detail":"event submission rejected with_reason: Cors"}
本地开发环境为 localhost:4200,已在 Sentry 项目设置中添加允许域名:
localhost:4200
Sentry 初始化代码(main.ts)
import { environment } from './environments/environment'; import {AppModule} from "./app/app.module"; import * as Sentry from "@sentry/angular-ivy"; Sentry.init({ dsn: "https://xxxxx@xxxxx.ingest.sentry.io/xxxxx", tracePropagationTargets: ["localhost", /^https:\/\/xxxxxxxx.ngrok-free.app/], integrations: [ new Sentry.BrowserTracing(), new Sentry.Replay({ maskAllText: false, blockAllMedia: false, }), ], // Performance Monitoring tracesSampleRate: environment.production ? 0.2 : environment.staging ? 0.5 : 1.0, // Capture 100% of the transactions, reduce in production! // Session Replay replaysSessionSampleRate: environment.production ? 0.1 : environment.staging ? 0.5 : 1.0, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production. replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur. });
检查 Sentry 域名配置格式
Sentry 的 CORS 允许列表需精确匹配,尝试添加不带端口的localhost,或带完整协议的http://localhost:4200/https://localhost:4200(根据本地开发使用的协议选择)。仅填写localhost:4200可能因缺失协议导致匹配失败。修复 Node 版本兼容性问题
Angular 13.x 官方支持的 Node 版本为 14.x 或 16.x,你当前使用的 18.16.0 不在支持范围内,版本不兼容可能引发网络请求底层处理异常。建议切换到 Angular 13 兼容的 Node LTS 版本(如 16.x)后重新测试。验证 Sentry SDK 与 Angular 版本匹配度
当前使用的@sentry/angular-ivy@7.66.0虽标注支持 Angular 12+,但可尝试降级到与 Angular 13 更适配的 SDK 版本(如 7.40.x 系列),避免版本不匹配引发的请求拦截问题。核对 DSN 正确性
检查初始化代码中的 DSN 是否完全符合 Sentry 项目配置,确保@符号前后的内容无拼写错误。错误的 DSN 可能导致请求被拦截,触发 CORS 相关报错。排查本地开发服务器 CORS 限制
即便 Sentry 端已配置允许域名,Angular 本地开发服务器的额外 CORS 限制也可能影响请求。可尝试在angular.json中添加代理配置,或使用--disable-host-check参数启动开发服务器,排除本地服务器的限制干扰。
内容的提问来源于stack exchange,提问作者Chris

