[英]How to fix: “undefined response from fetch” Javascript
一直在嘗試從以下指南中從開放的API中獲取鏈接/圖像: https : //discordjs.guide/additional-info/rest-api.html#using-node-fetch,但它不起作用。 我不斷收到不確定的回復。
已經嘗試制作異步函數等等,但是沒有更進一步。 還用try-catch子句將其包圍,以進行調試,但找不到答案。
module.exports = {
name: 'poes',
description: 'Laat een random poes foto zien',
async execute(message, args) {
const fetch = require('node-fetch');
const {body} = await fetch('https://aws.random.cat/meow').then(response => response.json());
message.channel.send(body.file);
},
};
這是它的使用位置:
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
}
);
遵循《指南》的預期結果應該是隨機的貓圖像。
您使用的文檔在兩種方面是錯誤的:
const {body} = await fetch('https://aws.random.cat/meow').then(response => response.json())
該行假定fetch
不會失敗(例如,使用404)。 這是一個普遍的錯誤,我曾在貧乏的小博客上寫下它 。 fetch
的promise只拒絕網絡錯誤 ,而不是HTTP錯誤。 您必須檢查response.ok
或response.status
。
解析的結果將具有body
屬性。
then
,它在async
函數中使用,這幾乎沒有意義。
但是,如果我轉到https://aws.random.cat/meow
,則會得到以下JSON:
{"file":"https:\/\/purr.objects-us-east-1.dream.io\/i\/img_20131111_094048.jpg"}
那里沒有body
,這就是為什么您對此undefined
的原因。
這是修復所有三個問題的示例:
const response = await fetch('https://aws.random.cat/meow');
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
const body = await response.json();
// ^---^---- no { and }, we don't want to destructure
api的響應是
{
"file": "https://purr.objects-us-east-1.dream.io/i/r958B.jpg"
}
你說的是
{
"body" : {
"file" : ""
}
}
所以你需要拋棄括號
const body = await fetch('https://aws.random.cat/meow')
.then(response => response.json());
或者您需要查找文件
const { file } = await fetch('https://aws.random.cat/meow')
.then(response => response.json());
console.log(file)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.