如何从 Node 的 fetch API 获取数据和错误消息?

问题描述 投票:0回答:1

我正在尝试使用 Node 的 18 fetch API 来调用 REST 服务器。

这是我的代码:

const get = () => {
    
  let response = await fetch("10.0.0.12/test", {
    method: "GET",
  });

  console.log("RESPONSE RECEIVED!!!!!!!!!!!!!!!");
  console.log(response)

  if (response.status !== 200) {
    let text = await response.text(); << Getting empty text
    console.log("STATUS TEXT: " + text);
    this.data = null;
  } else {
    let data = await response.json();
    console.log("DATA: "); << Getting no data at all
    console.log(data);
    if (res) this.data = data;
  }
};

无法获取状态文本或数据 - 解析时两者均为空......

输出:

RESPONSE RECEIVED!!!!!!!!!!!!!!!
Response {
  [Symbol(realm)]: null,
  [Symbol(state)]: {
    aborted: false,
    rangeRequested: false,
    timingAllowPassed: true,
    requestIncludesCredentials: true,
    type: 'default',
    status: 400,
    timingInfo: {
      startTime: 3119.011163998395,
      redirectStartTime: 0,
      redirectEndTime: 0,
      postRedirectStartTime: 3119.011163998395,
      finalServiceWorkerStartTime: 0,
      finalNetworkResponseStartTime: 0,
      finalNetworkRequestStartTime: 0,
      endTime: 0,
      encodedBodySize: 0,
      decodedBodySize: 0,
      finalConnectionTimingInfo: null
    },
    cacheState: '',
    statusText: 'This is a status text message test.',
    headersList: HeadersList {
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: null
    },
    urlList: [ [URL] ],
    body: { stream: undefined }
  },
  [Symbol(headers)]: HeadersList {
    [Symbol(headers map)]: Map(4) {
      'date' => 'Mon, 03 Oct 2022 18:54:39 GMT',
      'connection' => 'keep-alive',
      'keep-alive' => 'timeout=5',
      'content-length' => '0'
    },
    [Symbol(headers map sorted)]: null
  }
}

这是怎么回事?

javascript node.js fetch-api
1个回答
0
投票

尝试使用此模式并将代码放在这里

import fetch from 'node-fetch'

// async function
const get_geolocation = async () => {
    const url = 'https://geolocation-db.com/json/'
    let res = await fetch(url, {
        method: 'GET'
    })

    const data = await res.json()
    console.log(data)
}

// call the function
get_geolocation()

© www.soinside.com 2019 - 2024. All rights reserved.