简体   繁体   中英

React/Express Fetch Request Not Displaying Array of Json Objects

I have a React client trying to use the 'fetch' api to make a GET request to a node.js Express API I made. I have CORS enabled and have looked through many questions on here and cannot figure out why the get request will not display the data on my localhost React app. In the console log it displays In the console log it displays this...

 import React, { Component } from 'react'; export default class Drinker extends Component { constructor(props) { super(props); this.state = { data: [], isLoading: true, }; } componentDidMount(){ fetch('http://localhost:5000/api/getCustomers', { mode: 'no-cors', // 'cors' by default headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }}).then(response => { if (response.status >= 304) { return response.json(); } else { throw new Error('Something went wrong ...'); } }).then(data => { console.log(data.results); this.setState({ data: data.results, isLoading: false }); } ).catch(error => { console.log(error); this.setState({ error, isLoading: false }); }); } render(){ if(this.state.isLoading){ return( <h1> loading... </h1> ) } return( <ul> {this.state.data.map(drinker => <li> <p>{drinker.name}</p> </li> )} </ul> ); } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

I use postman and get a good request every time. This is my postman response to the url I'm making the fetch to...

{
"results": [
    {
        "name": "Jack",
        "address": "NJ"
    },
    {
        "name": "Steve",
        "address": "NJ"
    },
    {
        "name": "Denny",
        "address": "NJ"
    },
    {
        "name": "John",
        "address": "NJ"
    }
]
}

I figured out the answer, my Express app was sending responses as...

  res.status(200); // sends a status code
  res.json({results}); // sends results received from sql

but I changed it to this and it works now...

  res.status(200); // sends a status code
  res.send(JSON.stringify(results)); // sends results recieved from sql

I still don't really understand why it wouldn't work sent as json but sent as a string of text from Express, React now displays the data.

response.ok is true only if the status code is between 200-299. Since the request returns 304 it will be false . That's why data doesn't appear when you reload the page. Refer to the Mozilla documentation for the properties of response from the fetch API.

https://developer.mozilla.org/en-US/docs/Web/API/Response#Properties

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