簡體   English   中英

沒有從 Node JS 接收數據並在 React JS 中使用它

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

我試圖弄清楚如何連接 NodeJS 並將一些數據發送到 React JS 以供使用。 當我訪問后端時正在發送信息,但 React JS 收到一個空對象 {}。 我不確定我做錯了什么。 問題可能與CORS有關嗎? 還是我必須使用 JSON.parse(r)? 沒有把握。

索引.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

索引.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;

確保您已安裝 express 並初始化為 const 應用程序。 然后:

在后端:

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

在前端 - 內部 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> );
    }
  }

請更新您的類組件。 componentDidMount() 中的提取不符合預期。 您不需要在 fetch 中使用 await,因為這個異步操作一旦完成,狀態就會更新,並且 react 會呈現更新。 請注意您通過 API 發送的響應並相應地設置狀態。 在這里,我已經根據您在問題中提供的 api 示例設置了數據。 希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM