简体   繁体   中英

Not receiving the data from Node JS and use it in React JS

I'm trying to figure out how to connect NodeJS and send some data to React JS for it to use. The information is being sent when I access the backend, but React JS receives an empty object {}. I'm not sure what I'm doing wrong. Might the problem be related to CORS? Or do I have to use JSON.parse(r)? Not sure.

index.js

const a = "sup"

app.get("/", (req,res)=>{
    console.log("someone is here")
    res.status(200).json({
        data:a
    })
})


app.listen(3000, ()=>{
    console.log("Server is running")
})

Homepage.jsx

class Homepage extends Component {

    state = {
        authenticated: false,
        data:""
    };



    async componentDidMount(){
        const url = "http://localhost:3000"
        const r = await fetch(url, {
            mode: "no-cors",
            method: "GET",
            headers: 
              {"Access-Control-Allow-Origin": "*"}

          })
        const data = await JSON.stringify(r)
        console.log(data)
    }

    render() { 


        return ( <h1>{this.state.data}</h1> );
    }
}

UDPATE:

I had a port issue usage issue and incorrect usage of componentDidMount(). I managed to improve the code as recommended by users. NodeJS and ReactJS were pointing to port 3000. I reassigned the ports (NodeJS:3000, ReactJS:4000). ReactJS is now making a fetch call to " http://localhost:3000 ". However, I now get 2 errors:

1) Failed to load resource: net::ERR_EMPTY_RESPONSE
2) Uncaught (in promise) TypeError: Failed to fetch

index.js

const express = require("express")
const app = express()
const cors = require("cors")

const a = "sup"

app.use(cors({
        origin:"http://localhost:4000",
        methods:"GET,HEAD,PUT,PATCH,POST,DELETE",
        credentials:true
    }))

app.use((req,res,next)=>{
    res.header("Access-Control-Allow-Origin", "*")
    res.header("Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization")
})

app.get("/", (req,res)=>{
    console.log("someone is here")
    res.status(200).json({
        data:a
    })

})


app.listen(3000, ()=>{
    console.log("Server is running")
})

Homepage.jsx

import React, { Component } from 'react';

class Homepage extends Component {

    state = {
        data:[]
    };

     componentDidMount(){
        const url = "http://localhost:3000"
        fetch(url)
        .then(r=>r.json())
        .then(data=>this.setState({data}))

    }

    render() { 
        return ( <h1>{this.state.data ? this.state.data : "loading"}</h1> );
    }
}

export default Homepage;

Make sure you have express installed and initialised into const app. Then:

On the backend:

 const data = "Sup" app.use( "/", (req, res)=>{ res.status(200).send(data); } );

On the front end- Inside componentDidMount:

 const url="http://localhost:3000" axios.get(url).then(response => response.data) .then((data) => { this.setState({ data: data }) console.log(this.state.users) })

class Homepage extends Component {
 constructor(props){
 super(props);
 this.state = {
    authenticated: false,
    data: ""
  };

 }


  componentDidMount() {
    const url = "http://localhost:3000"
    fetch(url)
      .then(response => response.json())
      .then(data => this.setState({
        data: data
      }));
  }

  render() {
    return ( < h1 > {
        this.state.data ? this.state.data : 'loading';
      } < /h1> );
    }
  }

Please, update your class component. The fetch in componentDidMount() was not as expected. You need not use await in fetch because, this async action when ever its done, the state gets updated and react renders the updates. Please, watchout for the response you send via API and set the state accordingly. Here, I have set to data considering the api sample you have provided in the question. Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM