将 JSON 对象从 Express 服务器发送到 React 时未定义对象?

Kir*_*aru 3 node.js express reactjs

我是 React 和 Express 的新手。我在端口 8080 上使用localhost:8080/site3路由创建了客户端:

import React, { Component } from 'react';

export default class Site3 extends Component {
  componentDidMount() {
    console.log('FETCHING');
    fetch('http://localhost:3000/site3', {
      method: "GET"
    })
      .then(res => {
        res.json();
      })
      .then(result => {
        console.log(result);
        console.log('Finished fetching');
      });
  }

  render() {
    return content;
  }
}
Run Code Online (Sandbox Code Playgroud)

服务器端端口 3000:

const express = require("express");
require("dotenv").config();

const app = express();

const data = [
  { id: "tt0110357", name: "The Lion King", genre: "animation" },
  { id: "tt0068646", name: "The Godfather", genre: "crime" },
  { id: "tt0468569", name: "The Dark Knight", genre: "action" }
];

app.get("/site3", (req, res) => {
  console.log("RESPONDING");
  res.send(data);
});

// Port 3000
app.listen(process.env.PORT, () =>
  console.log(`Service 2 listening on port ${process.env.PORT}!`)
);
Run Code Online (Sandbox Code Playgroud)

启动 React 和 Express 服务器后,我访问了 localhost :8080/site3。Express 服务器收到客户端的请求,打印RESPONDINGJSON 数据并将其发送回 React。但是React无法获取JSON数据并返回undefined对象。

我该如何解决这个问题?

Tes*_*345 5

res.json() 调用中缺少 return 语句。

componentDidMount() {
    console.log('FETCHING');
    fetch('http://localhost:3000/site3', {
      method: "GET"
    })
      .then(res => {
       return res.json();
      })
      .then(result => {
        console.log(result);
        console.log('Finished fetching');
      });
  }
Run Code Online (Sandbox Code Playgroud)