Angular 13中如何绕过net::ERR_CERT_INVALID证书无效错误
Angular 13 绕过POST请求的net::ERR_CERT_INVALID证书错误
当前代码的问题
你把rejectUnauthorized放在请求头里是无效的——这个配置是Node.js HTTP模块的专属选项,Angular的HttpClient和浏览器根本不识别这个请求头,所以无法绕过证书验证。
开发环境解决方案(仅用于本地调试)
方法一:使用Angular代理(推荐)
这种方式通过Angular CLI的代理转发请求,由代理层忽略证书错误,是最可靠的本地调试方案。
- 在项目根目录创建
proxy.conf.json文件,内容如下:
{ "/sprintproject": { "target": "https://diallosuer:8443", "secure": false, "changeOrigin": true } }
secure: false:告诉代理忽略目标服务器的无效证书changeOrigin: true:确保请求头里的Host字段匹配目标服务器
- 修改
angular.json中的serve配置,添加代理文件路径:
"architect": { "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "你的项目名称:build", "proxyConfig": "src/proxy.conf.json" } } }
- 调整代码中的baseUrl为相对路径:
private baseUrl = '/sprintproject';
之后重启Angular开发服务器,请求会通过代理转发,不再触发证书错误。
方法二:自定义XHR工厂(局限性大)
部分浏览器(如Chrome)会强制验证证书,这种方法可能不生效,但可以尝试:
- 创建自定义XHR工厂类:
import { Injectable } from '@angular/core'; import { XhrFactory } from '@angular/common/http'; @Injectable() export class CustomXhrFactory implements XhrFactory { build(): XMLHttpRequest { const xhr = new XMLHttpRequest(); // 仅在本地开发环境下尝试禁用证书验证 if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') { // @ts-ignore 绕过TypeScript类型检查 xhr._restrictedHeaders = new Set([...xhr._restrictedHeaders, 'rejectUnauthorized']); } return xhr; } }
- 在
AppModule中替换默认的XhrFactory:
import { HttpClientModule, XhrFactory } from '@angular/common/http'; import { CustomXhrFactory } from './custom-xhr.factory'; @NgModule({ imports: [HttpClientModule], providers: [ { provide: XhrFactory, useClass: CustomXhrFactory } ] }) export class AppModule { }
生产环境注意事项
绝对不要在生产环境中绕过证书验证,这会导致请求数据被窃听或篡改,严重危害安全。正确做法是:
- 为服务器配置有效的SSL证书(比如Let's Encrypt提供免费证书)
- 确保证书在客户端浏览器中被信任
内容的提问来源于stack exchange,提问作者Alimou DIALLO
相关产品推荐
相关产品推荐

