加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular2-http – Angular2 HTTP – 如何理解后端服务器已关闭

发布时间:2020-12-17 08:33:42 所属栏目:安全 来源:网络整理
导读:我正在开发一个前端,它使用服务器提供的 JSON服务. 我很高兴使用Angular2的HTTP,我可以通过.catch()运算符捕获错误. 如果我发现与特定服务相关的问题(例如,服务未由服务器定义),catch()操作符将收到状态为404的响应,并且我可以轻松地管理该情况. 另一方面,如
我正在开发一个前端,它使用服务器提供的 JSON服务.

我很高兴使用Angular2的HTTP,我可以通过.catch()运算符捕获错误.

如果我发现与特定服务相关的问题(例如,服务未由服务器定义),catch()操作符将收到状态为404的响应,并且我可以轻松地管理该情况.

另一方面,如果服务器完全关闭,catch()操作符将收到状态代码为200的响应,并且没有与问题原因相关的特定符号或文本(即整个服务器已关闭).
在控制台上,我看到angular(http.dev.js)写了一条消息net :: ERR_CONNECTION_REFUSED,但我不知道如何在我的代码中做一些类似的事情(即了解正在发生的事情并做出适当的反应).

任何帮助,将不胜感激.

如果您想在您的应用程序中全局处理此事件,我建议使用略有修改的Nicolas Henneaux的答案 https://stackoverflow.com/a/37028266/1549135

基本上你可以检查error.status === 0,当发生net :: ERR_CONNECTION_REFUSED错误时会发生这种错误.

完整的模块文件:

import { Request,XHRBackend,BrowserXhr,ResponSEOptions,XSRFStrategy,Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

export class AuthenticationConnectionBackend extends XHRBackend {

  constructor(_browserXhr: BrowserXhr,_baseResponSEOptions: ResponSEOptions,_xsrfStrategy: XSRFStrategy) {
    super(_browserXhr,_baseResponSEOptions,_xsrfStrategy);
  }

  createConnection(request: Request) {
    let xhrConnection = super.createConnection(request);
    xhrConnection.response = xhrConnection.response.catch((error: Response) => {
      if (error.status === 0){
        console.log("Server is down...")
      }
      ...
      return Observable.throw(error);
    });
    return xhrConnection;
  }

}

模块文件:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule,XHRBackend } from '@angular/http';
import { AppComponent } from './app.component';
import { AuthenticationConnectionBackend } from './authenticated-connection.backend';

@NgModule({
    bootstrap: [AppComponent],declarations: [
        AppComponent,],entryComponents: [AppComponent],imports: [
        BrowserModule,CommonModule,HttpModule,providers: [
        { provide: XHRBackend,useClass: AuthenticationConnectionBackend },})
export class AppModule {
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读