Angular 17.3.8非独立项目ngOnInit触发请求VSCode控制台报403错误
Angular 17.3.8非独立项目403错误排查问题
问题背景
- 基于Cookie实现的登录系统运行正常:后端发送Cookie后,Angular的POST、PUT、GET、DELETE请求均能正常携带凭证,接口返回结果符合预期。
- 通过HTML按钮点击触发
getAll()方法时,请求完全正常,无任何错误。 - 将
getAll()移到ngOnInit中调用时,浏览器能正常渲染数据,但VSCode控制台抛出403 HttpErrorResponse错误。
代码对比
按钮触发版本(运行正常)
组件代码:
export class AvailableCodesComponent { codesThirtyMinutes: Code[] = []; codesEightHours: Code[] = []; constructor(private codeService: CodeService ) { } public getAll(){ this.codeService.getAllCodes().subscribe( (codes: any) => { console.log(codes); }, (error: any) => { console.log(error); } ); } }
HTML代码:
<button (click)="getAll()">GetAll</button>
ngOnInit调用版本(控制台报错)
组件代码:
export class AvailableCodesComponent implements OnInit{ codesThirtyMinutes: Code[] = []; codesEightHours: Code[] = []; constructor(private codeService: CodeService ) { } ngOnInit(): void { this.getAll(); } public getAll(){ this.codeService.getAllCodes().subscribe( (codes: any) => { console.log(codes); }, (error) => { console.error(error); } ); } }
控制台错误信息
{ status: 403, statusText: 'Unknown Error', url: 'http://localhost:8080/code/getall', ok: false, name: 'HttpErrorResponse', message: 'Http failure response for http://localhost:8080/code/getall: 403 ', error: null }
疑问
- 凭证有效且每个请求均携带Cookie,为何仅ngOnInit调用时控制台报错?
- 是否可以忽略此错误?该如何处理?
内容的提问来源于stack exchange,提问作者Francis
相关产品推荐
相关产品推荐

