Как вывести информацию json импортированную через JS, чтобы в дальнейшем можно было преобразовать в текст на html странице?
Нет, это не дубликат данного вопроса. У меня другая проблема.
Реализовал небольшое API для самообразования. После этого загружаю его себе на localhost:3000.
Затем я создаю в отдельной папке легендарное "трио" из html, css b js. Вот, собственно код импорта в JS.
fetch("http:/localhost:3000")
.then((result) => {
return result.json();
})
.then((data) => {
console.log(data);
});
И вот собственно вопрос: каким именно методом я могу оперировать полученный данные? Понимаю, вопрос наверняка глупый, однако хотелось бы получить либо ответ, либо ссылку на ресурс с описанием решения. Заранее огромное вам спасибо!
P.S. API представляет у меня из себя просто возможность подавать запрос в базу данных MongoDB и записывать/изменять/удалять оттуда данные.
Вот пример моего лога консоли:
(4) [{…}, {…}, {…}, {…}]
0:
date: "2020-07-10T13:31:34.504Z"
description: "That worked"
title: "The testing of the MongoDB"
__v: 0
_id: "5f086db67cfb94f8143fe642"
__proto__: Object
1:
date: "2020-07-10T14:07:22.108Z"
description: "That worked, but with using async now."
title: "The testing of the MongoDB"
__v: 0
_id: "5f08761a83c659f5e0423d78"
__proto__: Object
2:
date: "2020-07-10T14:13:28.756Z"
description: "That worked, but with using async now. And using the listing of all posts."
title: "The testing of the MongoDB"
__v: 0
_id: "5f087788b3fa81d9281f65ec"
__proto__: Object
3:
date: "2020-07-10T14:51:24.254Z"
description: "This will be updated"
title: "Updated"
__v: 0
_id: "5f08806cb6a83dff58968f0f"
__proto__: Object
length: 4
__proto__: Array(0)
Ответы (1 шт):
Решил эту проблему не через fetch, а через XMLHttpRequest.
Вот, что получилось в конечном итоге, чисто для примера. Вытащил из json Имя и описание первого объекта.
const requestURL = "http://localhost:3000";
const request = new XMLHttpRequest();
request.open("GET", requestURL);
request.responseType = "json";
request.send();
request.onload = function () {
const jsonDB = request.response;
makeTitles(jsonDB);
makeDescriptions(jsonDB);
console.log(request.response);
};
function makeTitles(jsonObj) {
let title = document.createElement("h1");
title.textContent = jsonObj[0]["title"];
document.getElementById("header").appendChild(title);
}
function makeDescriptions(jsonObj) {
let description = document.createElement("h2");
description.textContent = jsonObj[0]["description"];
document.getElementById("header").appendChild(description);
}