Kiro Hikaru
Kiro Hikaru

Reputation: 63

Undefined object when sending a JSON object from Express server into React?

I am new to React and Express. I had created client side on port 8080 with localhost:8080/site3 route:

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;
  }
}

and server side on port 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}!`)
);

After starting both React and Express server, I went to the localhost:8080/site3. The Express server had get the request from the client, printed RESPONDING and sent a JSON data back to React. But the React cannot get the JSON data and return to undefined object.

How do I solve this?

Upvotes: 3

Views: 588

Answers (2)

You can leave the curly brackets from the first .then() like the following:

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

Upvotes: 1

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

return statement is missing in the res.json() call.

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');
      });
  }

Upvotes: 5

Related Questions