Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 将JSON对象从Express server发送到React时未定义对象?_Node.js_Reactjs_Express - Fatal编程技术网

Node.js 将JSON对象从Express server发送到React时未定义对象?

Node.js 将JSON对象从Express server发送到React时未定义对象?,node.js,reactjs,express,Node.js,Reactjs,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

我是新的反应和表达。我在端口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;
  }
}
和端口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}!`)
);
启动React和Express服务器后,我转到本地主机:8080/site3。 Express服务器从客户机获取请求,打印出响应的JSON数据并发送回React。 但是React无法获取JSON数据并返回到
undefined
对象


如何解决此问题?

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


可以将第一个.then()中的花括号保留为如下所示:

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

kiro可以在网络选项卡中检查api响应,或者在此处附加屏幕吗?最可能的问题是在保留响应的React端,但在first then block中,您没有返回任何内容,这就是为什么在necxt then block中无法得到结果的原因
componentDidMount() {
    console.log('FETCHING');
    fetch('http://localhost:3000/site3', {
      method: "GET"
    })
      .then(res => res.json())
      .then(result => {
        console.log(result);
        console.log('Finished fetching');
      });
  }