0

So, I am getting the below error,

inspected via google chrome

enter image description here

What I am trying to achieve is to explore the Fetch Api by retrieving some data via userApi.js file which pulls it from a srcServer.js (I have hardcoded some data here). I am using webpack bundle and index is the entry point of my project. I have created index.html to bind the data via innerhtml.

Earlier I was using import 'isomorphic-fetch' in my userApi.js file but that too didn't help and hence I found some suggestions on google to use isomorphic-fetch, node-fetch etc. nothing of that sort worked.

I have added most of the artifacts below can you please guide me what is that I am missing here.

Project Structure

enter image description here

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' }
  ])
})
4

1 回答 1

1

该错误为您提供了确切的原因,即user未定义。您是否尝试console.log(element);在 forEach 循环中打印?你会看到你需要改变什么。

您访问的用户信息不正确。在您的 forEach 循环中,每个值都表示为elementnotuser

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
  })
于 2018-08-17T15:37:06.530 回答