【发布时间】:2020-07-25 10:57:36
【问题描述】:
我的代码是
var api_url
$.getJSON("https://api.ipify.org/?format=json", function(e) {
myIP = e.ip;
//api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
});
//api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
function geoloc() {
api_url = "https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=" + myIP
console.log(api_url)
const response = await fetch(api_url)
const data = await response.json();
console.log(data)
}
geoloc();
我用 python 3 的 http.server 启动了它,它打印了"https://cors-anywhere-ctrack.herokuapp.com/https://tools.keycdn.com/geo.json?host=undefined",并且正如预期的那样,获取失败了。经过仔细检查,定义了变量 myIP。我觉得它与异步和等待有关,但我不确定。
【问题讨论】:
-
如果您使用的是 async/await,那么您的
geoloc函数应声明为async function geoloc()。 -
@lawrence-witt 很抱歉造成混乱。我不确定如何应用 async / await 或是否应该应用。
标签: javascript asynchronous fetch-api