简体   繁体   English

没有从 Node JS 接收数据并在 React JS 中使用它

[英]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.我试图弄清楚如何连接 NodeJS 并将一些数据发送到 React JS 以供使用。 The information is being sent when I access the backend, but React JS receives an empty object {}.当我访问后端时正在发送信息,但 React JS 收到一个空对象 {}。 I'm not sure what I'm doing wrong.我不确定我做错了什么。 Might the problem be related to CORS?问题可能与CORS有关吗? Or do I have to use JSON.parse(r)?还是我必须使用 JSON.parse(r)? Not sure.没有把握。

index.js索引.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主页.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: UDPATE:

I had a port issue usage issue and incorrect usage of componentDidMount().我有一个端口问题使用问题和 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). NodeJS 和 ReactJS 指向端口 3000。我重新分配了端口 (NodeJS:3000, ReactJS:4000)。 ReactJS is now making a fetch call to " http://localhost:3000 ". ReactJS 现在正在对“ http://localhost:3000 ”进行 fetch 调用。 However, I now get 2 errors:但是,我现在收到 2 个错误:

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

index.js索引.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主页.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.确保您已安装 express 并初始化为 const 应用程序。 Then:然后:

On the backend:在后端:

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

On the front end- Inside componentDidMount:在前端 - 内部 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. componentDidMount() 中的提取不符合预期。 You need not use await in fetch because, this async action when ever its done, the state gets updated and react renders the updates.您不需要在 fetch 中使用 await,因为这个异步操作一旦完成,状态就会更新,并且 react 会呈现更新。 Please, watchout for the response you send via API and set the state accordingly.请注意您通过 API 发送的响应并相应地设置状态。 Here, I have set to data considering the api sample you have provided in the question.在这里,我已经根据您在问题中提供的 api 示例设置了数据。 Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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