【发布时间】:2020-10-24 09:07:51
【问题描述】:
我在 React 中有以下与第三方 api 交互的代码。当 Avaya One-X 客户端未在目标 PC 上运行时,我在控制台中收到错误连接被拒绝,这是正常的。问题是代码设置为每 5 秒运行一次,每当 one-x 客户端未运行时,控制台就会充满这些错误。
我怎样才能更好地处理这个问题?不记录这么多次就好了。
fetchData = (url) => {
return new Promise((res, rej) => {
fetch(url)
.then((r) => r.text())
.then((text) => {
res(text);
})
.catch((e) => rej(e));
});
};
getLogs = async () => {
try {
const { user } = this.props.auth;
const regxmlPromise = this.fetchData(
`http://127.0.0.1:60000/onexagent/api/registerclient?name=${user.id}`
);
const clientIdPromise = this.fetchData(
`/api/avaya/${user.id}/getclientid/`
);
const resolves = await Promise.all([regxmlPromise, clientIdPromise]);
const [registration, clientId] = resolves || [];
const nextNotification = await this.fetchData(
`http://127.0.0.1:60000/onexagent/api/nextnotification?clientid=${clientId}`
);
if (registration) {
const regxml = new XMLParser().parseFromString(registration);
if (regxml.attributes.ResponseCode === "0") {
axios.post(`/api/avaya/${user.id}/register/`, regxml);
console.log("ClientId sent!");
}
}
if (nextNotification) {
const xml = new XMLParser().parseFromString(nextNotification);
if (
xml.children[0].name === "VoiceInteractionCreated" ||
xml.children[0].name === "VoiceInteractionMissed" ||
xml.children[0].name === "VoiceInteractionTerminated"
) {
console.log(xml);
console.log(xml.children[0].name);
axios.post(`/api/avaya/${user.id}/logcalls/`, xml);
}
}
} catch (error) {
console.log(error);
}
};
timer = (time) => {
const date = new Date(time);
return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
};
componentDidMount() {
this.getLogs();
this.callsInterval = setInterval(this.getLogs, 5000);
}
componentWillUnmount() {
clearInterval(this.callsInterval);
}
为了让事情更清楚,这里是控制台的屏幕截图。我收到连接被拒绝的 Get 错误以及我捕获并记录的实际错误。因此,即使我发现错误并且什么都不做,无论如何我仍然会在控制台中拒绝连接。
一个有趣的事情是,如果我使用 fetch-node,我会得到不同的行为和错误消息。 node 的错误是一个对象并且具有不同的道具。在 React 中,如果我 console.log 获取请求错误,我只会得到“TypeError: Failed to fetch”
【问题讨论】:
标签: javascript node.js reactjs fetch fetch-api