首页 > 解决方案 > 如何修复 fetch() 方法引发的无法获取错误?

问题描述

我在 localhost 上有一个单独的基本 nodejs 服务器和一个单独的前端。

当我在服务器离线时尝试获取时,fetch()抛出failed to fetch * 错误。因此,为此,我尝试通过检查响应来处理或捕获该错误。好的,喜欢

if (!response.ok) throw Error(response.statusText)

尽管它捕获了错误,但它仍然会引发错误。即使我试图控制台记录它。

if (!response.ok) return console.log(response.statusText)

这里是接口。

export interface 
CommunicatorParameter {
  endUrl: string;
}

interface ErrorResponse {
  message: string;
}

interface V01List {
  tittle: string;
  url: string;
}

type V01ListData = Array<V01List>;
type ReleasedVersionsResponse = Array<string>;
type CurrentVersionResponse = string;

interface SuccessResponse{
  data: V01ListData | ReleasedVersionsResponse | CurrentVersionResponse ;
}

export type ServerResponse = SuccessResponse | ErrorResponse;
export type CommunicatorResponse = SuccessResponse['data'];

下面是帮助与服务器通信的服务功能。另外,我希望这个函数应该返回直接数据(键)值。

interface SuccessResponse{
  data: V01ListData | ReleasedVersionsResponse | CurrentVersionResponse ;
}
// fetchDataFromServer.ts

// these are type and interfaces.
import { CommunicatorParameter, ServerResponse, CommunicatorResponse } from "./declarations/index.js";

// These are helper functions
import { buildValidURL, checkForBadResponse } from "./helpers/index.js";

export async function fetchDataFromServer({ endUrl }: CommunicatorParameter): Promise<CommunicatorResponse> {
  const fullURL = buildValidURL(endUrl);
  
  const response = await fetch(fullURL, {
    method: 'GET'
  });
  console.log(response.headers)
  const jsonParsedData = <ServerResponse>await response.json();
  
//This function simply checks response and throws an error if the response is not ok.
  checkForBadResponse(response, jsonParsedData);
  
// Here I am doing this because if I return from try/catch or if statement the return type of function does not match and typescript complain about that. I don't think it is a good way to do it. But don't know how to do it.

  return ('data' in jsonParsedData) ? jsonParsedData.data : [];
}

我还有另一个函数可以帮助从使用上述通信器乐趣的服务器获取版本数据。

// fetchCurrentVersion.ts

import { fetchDataFromServer } from "../services/fetchDataFromServer.js";

export async function fetchCurrentListVersion() {
  const END_URL = "/current_version";
  
  try {
    const response = await fetchDataFromServer({ endUrl: END_URL });

// Here I am checking the type of response/data which is returned by communicator as my need, see the interface SuccessResponse data key.

    if (typeof response === 'string') {
      return response;
    }
  } catch (error) {
    console.log(error.message)
  }
  // fallback return value;
  return "v0.0";
}

这种方法好吗?我觉得仍然有更好的方法来做到这一点。如果你能帮忙,请

标签: javascriptnode.jstypescript

解决方案


推荐阅读