【问题标题】:unable to display data using fetch API - node.js无法使用 fetch API 显示数据 - node.js
【发布时间】:2018-08-17 15:28:16
【问题描述】:

所以,我收到以下错误,

通过谷歌浏览器检查

我想要实现的是通过 userApi.js 文件检索一些数据来探索 Fetch Api,该文件从 srcServer.js 中提取数据(我已经硬编码这里有一些数据)。我正在使用 webpack 包,index 是我项目的入口点。我创建了 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>&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' }
  ])
})

【问题讨论】:

    标签: node.js fetch es6-promise isomorphic-fetch-api


    【解决方案1】:

    错误给出了确切的原因,即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
      })
    

    【讨论】:

    • 哈哈...就是这样,我从早上开始就很傻地在做很多事情,看起来需要一杯咖啡。无论如何,感谢您指出我这一点。我在敲我的头。
    猜你喜欢
    • 2021-09-12
    • 2018-07-20
    • 2020-05-08
    • 2021-10-24
    • 2017-11-26
    • 2021-04-18
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    相关资源
    最近更新 更多