[英]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.