首页 > 解决方案 > 没有从 Node JS 接收数据并在 React JS 中使用它

问题描述

我试图弄清楚如何连接 NodeJS 并将一些数据发送到 React JS 以供它使用。当我访问后端时正在发送信息,但 React JS 收到一个空对象 {}。我不确定我做错了什么。问题可能与CORS有关吗?还是我必须使用 JSON.parse(r)?没有把握。

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")
})

主页.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:

我遇到了端口问题使用问题和 componentDidMount() 的错误使用。我设法按照用户的建议改进了代码。NodeJS 和 ReactJS 指向端口 3000。我重新分配了端口(NodeJS:3000,ReactJS:4000)。ReactJS 现在正在对“ http://localhost:3000 ”进行 fetch 调用。但是,我现在收到 2 个错误:

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")
})

主页.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;

标签: javascriptnode.jsreactjs

解决方案


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

请更新您的课程组件。componentDidMount() 中的提取不如预期。您不需要在 fetch 中使用 await,因为这个异步操作一旦完成,状态就会更新,并且 react 会呈现更新。请注意您通过 API 发送的响应并相应地设置状态。在这里,考虑到您在问题中提供的 api 示例,我已经设置了数据。希望这可以帮助!


推荐阅读