javascript - 使用 fetch api 传递 url 变量
问题描述
我正在尝试通过 api fetch 传递一个 url 变量,但我无法获得任何结果。谢谢,我是 Javascript 的新手。
//Get IP address
fetch('https://extreme-ip-lookup.com/json/')
.then((eip) => {
return eip.json();
}).then((eip) => {
document.getElementById('ip').value = eip.query;
var myip = document.getElementById('ip').value;
var url = "https://api.pray.zone/v2/times/today.json?ip=" + myip;
})
//Get City
fetch(url)
.then((res) => {
return res.json();
}).then((res) => {
document.getElementById('city').value = res.results.location.city;
})
我可以获取 IP 地址,但不能获取城市。
解决方案
url
仅在.then
回调中可见,甚至在您第二次调用fetch
.
在那里调用第二个fetch
并返回返回的承诺,fetch
以便您可以正确链接它们:
//Get IP address
fetch('https://extreme-ip-lookup.com/json/')
.then((eip) => {
return eip.json();
})
.then((eip) => {
document.getElementById('ip').value = eip.query;
var myip = document.getElementById('ip').value;
return fetch("https://api.pray.zone/v2/times/today.json?ip=" + myip);
})
//Get City
.then((res) => {
return res.json();
})
.then((res) => {
document.getElementById('city').value = res.results.location.city;
})
推荐阅读
- delphi - Delphi Tokyo Service 仅在启动时创建进程
- r - 如何在 Github 的 Atom 中更新 R 的路径变量?
- java - 如何修复 Firebase 身份验证中的空指针异常?
- python-2.7 - 变量引用和可变性
- google-chrome-extension - 如何使用 chrome.tabs.executeScript() 更改网页
- python - 如何使 QPushButtons 将文本添加到 pyqt5 中的 QLineEdit 框中?
- angular - 无法将 Firebase Auth 连接到 Angular Web App,页面仅重新加载
- reactjs - redux-saga+next.js:动作被触发,但 store 无法访问并被冻结
- visual-studio-code - 是否可以在 VSCode 中侦听/拦截与打字稿语言服务器之间的 LSP 消息?
- python-3.x - TensorFlow 2.0 中 lambda 函数的组合