首页 > 解决方案 > 仅显示 [object object],不使用子路径显示来自 api 端点的数据

问题描述

我正在使用 API 来绘制数据 var city = window.location.pathname; var url = '//apiurl';

var infoCity = document.getElementById("info")

fetch(url).then(response => {
    return response.json();
}).then(data => {
    data.innerHTML += data;
    console.log(data);
}).catch(err => {
    console.log("there is an error")
});

这让我得到了数据,但它没有在我的 html 文件中显示数据,我在其中有一个 id 为“info”的 div。

相反,它只是说 [Object Object],这是我的第一个问题。

其次,如果用户键入 mysite.com/key,我想根据该键显示数据

我有一个 HTTP 服务器设置,但是当我输入 localhost.com/8080/key 时它不起作用。

但是,对响应进行硬编码,例如

var url = '//apiurl/specifickey' gets the data.

标签: javascripthtmlapiobjectfetch

解决方案


info 变量的上下文需要更改。

var city = window.location.pathname;
console.log(city);

var url = '//restcountries.eu/rest/v2/capital' + city;
const info = document.querySelector("#info");

fetch(url).then(response => {
    return response.json();
}).then(data => {
    info.innerHTML = data;
    console.log(data);
}).catch(err => {
    console.log("there is an error")
});

推荐阅读