[英]How to parse an object obtained through a Axios GET request Node.js Express
我正在通過 axios 獲取請求和 I'. 試圖檢索結果數組中每個 object 的名稱屬性。 當我在控制台記錄它時,它給了我一個未定義的錯誤? 但是,如果我控制台記錄 data.results,我會看到完整的對象列表嗎?
Api 使用 - https://rickandmortyapi.com/api/character
module.exports = (app) => {
app.get("/api/users/london", async (req, res) => {
axios
.get("https://rickandmortyapi.com/api/character")
.then(({ data }) =>
console.log(
data.array.forEach((element) => {
element.name;
})
)
)
.catch((err) => {
console.log(err);
});
});
};
TypeError: Cannot read property 'forEach' of undefined
at /Users/user/workspace/morty- demo/routes/userRoutes.js:20:22
at processTicksAndRejections (internal/process/task_queues.js:97:5)
使用 map 查詢每個名稱屬性
console.log(
data.array.map((element) => {
return element.name;
})
)
您正在嘗試訪問似乎不是data.array
返回的數據的屬性的 data.array。 您想在數組本身data.results
.forEach
這個修改后的代碼應該可以工作,盡管它可能需要一些調整。
app.get("/api/users/london", async (req, res) => {
axios
.get("https://rickandmortyapi.com/api/character")
.then(({ data }) =>
data.results.forEach((element) => {
console.log(element.name);
})
)
.catch((err) => {
console.log(err);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.