无法使用 fetch API - node.js 显示数据

unable to display data using fetch API - node.js

所以,我收到以下错误,

inspected via google chrome

我想要实现的是通过 userApi.js 文件检索一些数据来探索 Fetch Api,该文件从 srcServer.js(我在这里硬编码了一些数据)。我正在使用 webpack bundle,index 是我项目的入口点。我创建了 index.html 以通过 innerhtml 绑定数据。

早些时候我在 userApi.js 文件中使用 import 'isomorphic-fetch' 但这也没有帮助,因此我在 google 上找到了一些使用同构获取、节点获取的建议等等。没有那种工作。

我已经添加了下面的大部分工件,你能指导我这里缺少什么吗?

Project Structure

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>&nbsp;</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 未定义。您是否尝试在 forEach 循环中打印 console.log(element); ?您将看到需要更改的内容。

您访问的用户信息有误。在您的 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
  })