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

React组件中如何获取HTTP响应的status状态码?

问题:获取登录接口的HTTP响应状态码

我在Login组件中调用LoginService的login方法,代码如下:

const result = await this.context.loginService.login({
    username: this.state.password!,
    password: this.state.password!,
});

现在需要从返回的result中拿到HTTP响应的状态码。

LoginService的login方法代码

public async login(credentials: Credentials) {
return firstValueFrom(
  from(
    this.httpService.fetch<{ jwt: string }>(
      `${this.apiUrl}employees/login`,
      HttpMethod.POST,
      {
        username: btoa(credentials.username),
        password: btoa(credentials.password),
      }
    )
  ).pipe(
    switchMap((result) =>
      result?.jwt ? this.authService.saveToken(result.jwt) : of(null)
    ),
    switchMap((token) =>
      token ? this.authService.getToken(true) : of(null)
    ),
    map((decoded) => decoded?.userid || null),
    first(),
    catchError(() => of(null))
  )
)
}

HttpService的fetch方法代码

public async fetch<T>(
url: string,
method: HttpMethod,
body?: Record<string, unknown> | Array<Record<string, unknown>>,
header?: Record<string, unknown>,
responseTypeJson = true
  ): Promise<T> {
    const token = await lastValueFrom(
      this.authService.getToken(false).pipe(first())
    );
    const authHeader = token ? { Authorization: `Bearer ${token}` } : undefined;
    const headers = {
      ...(method !== HttpMethod.GET
        ? { "Content-Type": "application/json" }
        : undefined),
      ...authHeader,
      ...header,
    };
    const response = await fetch(url, {
      method,
      headers,
      body: JSON.stringify(body),
    });
    return responseTypeJson && response ? ((await response.json().catch(() => response)) as T) : (response as T);
  }

修改方案

要获取HTTP状态码,需要调整HttpService的fetch方法,让它返回包含响应数据和状态码的结构,再逐层修改上层逻辑传递状态码。

1. 修改HttpService的fetch方法

先定义通用返回类型,让方法返回包含data和status的对象:

// 定义通用响应结构
interface FetchResponse<T> {
  data: T;
  status: number;
}

public async fetch<T>(
url: string,
method: HttpMethod,
body?: Record<string, unknown> | Array<Record<string, unknown>>,
header?: Record<string, unknown>,
responseTypeJson = true
  ): Promise<FetchResponse<T | Response>> {
    const token = await lastValueFrom(
      this.authService.getToken(false).pipe(first())
    );
    const authHeader = token ? { Authorization: `Bearer ${token}` } : undefined;
    const headers = {
      ...(method !== HttpMethod.GET
        ? { "Content-Type": "application/json" }
        : undefined),
      ...authHeader,
      ...header,
    };
    const response = await fetch(url, {
      method,
      headers,
      body: JSON.stringify(body),
    });

    let data;
    if (responseTypeJson && response) {
      data = await response.json().catch(() => response);
    } else {
      data = response;
    }

    // 返回包含状态码和数据的对象
    return {
      data: data as T,
      status: response.status
    };
  }

2. 修改LoginService的login方法

调整方法逻辑,接收fetch返回的状态码,最终返回包含用户ID和状态码的结果:

// 定义login方法的返回结构
interface LoginResult {
  userId: string | null;
  statusCode: number;
}

public async login(credentials: Credentials): Promise<LoginResult> {
return firstValueFrom(
  from(
    this.httpService.fetch<{ jwt: string }>(
      `${this.apiUrl}employees/login`,
      HttpMethod.POST,
      {
        username: btoa(credentials.username),
        password: btoa(credentials.password),
      }
    )
  ).pipe(
    switchMap((fetchResponse) => {
      if (fetchResponse.data?.jwt) {
        return this.authService.saveToken(fetchResponse.data.jwt).pipe(
          map(() => ({ statusCode: fetchResponse.status, jwt: fetchResponse.data.jwt }))
        );
      } else {
        return of({ statusCode: fetchResponse.status, jwt: null });
      }
    }),
    switchMap(({ statusCode, jwt }) => {
      if (jwt) {
        return this.authService.getToken(true).pipe(
          map(decoded => ({ statusCode, userId: decoded?.userid || null }))
        );
      } else {
        return of({ statusCode, userId: null });
      }
    }),
    first(),
    catchError(() => of({ statusCode: 500, userId: null }))
  )
)
}

3. 在Login组件中获取状态码

现在调用login方法后可直接拿到状态码:

// 修正原代码笔误:username应对应state.username
const result = await this.context.loginService.login({
    username: this.state.username!,
    password: this.state.password!,
});

// 获取状态码和用户ID
const { statusCode, userId } = result;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:25:23