[英]using fetch api function to get data from MongoDB and display them in node.js
[英]unable to display data using fetch API - node.js
所以,我收到以下錯誤,
通過谷歌瀏覽器檢查
我想要達到的目的是通過通過userApi.js文件檢索一些數據來探索Fetch Api, 該文件是從srcServer.js中提取數據的(我已經在此處硬編碼了一些數據)。 我正在使用webpack捆綁包, 索引是我項目的入口。 我創建了index.html以通過innerhtml綁定數據。
早些時候,我在userApi.js文件中使用了import 'isomorphic-fetch'
,但這也無濟於事,因此我在Google上發現了一些建議,以使用isomorphic-fetch,node-fetch等。
我添加了下面的大多數工件,您能否指導我在這里缺少的內容。
項目結構
userApi.js
import 'isomorphic-fetch'
import 'es6-promise'
export function getUsers () {
return get('users')
}
function get (url) {
return fetch(url).then(onSuccess, onError) //eslint-disable-line
}
function onSuccess (response) {
return response.json()
}
function onError (error) {
console.log(error)
}
index.js
/* eslint-disable */ // --> OFF
import './index.css'
import {getUsers} from './api/userApi'
// Populate table of users via API call.
getUsers().then(result => {
let usersBody = ''
result.forEach(element => {
usersBody+= `<tr>
<td><a href='#' data-id='${user.id}' class='deleteUser'>Delete</a></td>
<td>${user.id}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
</tr>` //eslint-disable-line
})
global.document.getElementById('users').innerHTML = usersBody
})
的index.html
<!DOCTYPE <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Users</h1>
<table>
<thead>
<th> </th>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody id="users">
</tbody>
</table>
<script src="bundle.js"></script>
</body>
</html>
srcServer.js
// sample api call data
app.get('/users', function (req, res) {
// Hard coded for simplicity
res.json([
{ 'id': 1, 'firstName': 'P', 'lastName': 'K' },
{ 'id': 2, 'firstName': 'M', 'lastName': 'K' },
{ 'id': 3, 'firstName': 'S', 'lastName': 'K' }
])
})
錯誤是給您確切的原因,即未定義user
。 您是否嘗試打印console.log(element);
在您的forEach循環中? 您將看到需要更改的內容。
您正在錯誤地訪問用戶信息。 在forEach循環中,每個值都表示為element
而不是user
result.forEach(element => {
usersBody+= `<tr>
<td><a href='#' data-id='${element.id}' class='deleteUser'>Delete</a></td>
<td>${element.id}</td>
<td>${element.firstName}</td>
<td>${element.lastName}</td>
</tr>` //eslint-disable-line
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.