简体   繁体   中英

ReactJS receiving empty array from NodeJS

I'm trying to send some simple data from the backend to the ReactJS API. However, ReactJS doesn't seem to receive it. ReactJS just receives an empty string. This is the code for both. Node is running in port 3000 and React on port 4000.

index.js

const express = require("express")
const app = express()
const cors = require("cors")
const a = "Hello world"


// app.use(cors())
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.json({
        data:a
    })

})


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

Homepage.jsx

import React, { Component } from 'react'
import axios from 'axios'

class Homepage extends Component {

    state = {
        authenticated: false,
        data:[]
    };

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

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

export default Homepage;

The issue is with your node server.

You have defined a middleware to set specific response headers.

// This block.
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")
})

The issue is that you are not invoking the next parameter on the callback function, hence the middleware is not passing control to the next middleware (in your case, the route handlers)

The fix:

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

    next();  // Add this line
})

One important note about express middlewares:

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging

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