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



我正在尝试使用Node的18获取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;
}
};

无法获取状态文本或数据-解析时两者都为null。。。。

输出:

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
}
}

这是怎么回事?

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

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()

相关内容

  • 没有找到相关文章

最新更新