这可能是因为第二个请求发生在第一个请求完成之后。为了确保第二个请求的成功,可以在第一个请求之后使用Promise或回调来执行第二个请求。以下是一个使用Promise的代码示例:
// 第一个请求
fetch('https://example.com/api/request-one')
.then(response => response.json())
.then(data => {
// 更新变量
const myVariable = data.myVariable;
// 执行第二个请求
return fetch(`https://example.com/api/request-two?variable=${myVariable}`);
})
.then(response => response.json())
.then(data => {
// 输出正确信息
console.log(data);
})
.catch(error => {
console.error(error);
});
在这个示例中,第二个请求发生在第一个请求之后,并且使用了第一个请求返回的变量来构建URL。如果第一个请求成功,第二个请求将接收正确的信息并输出。如果第一个请求失败,整个Promise链都将进入拒绝状态。
如果不想使用Promise,也可以使用回调函数来实现类似的操作。
上一篇:API请求未经过身份验证
下一篇:API请求为什么会被调用4次?