[英]React/Express Fetch Request Not Displaying Array of Json Objects
我有一個React客戶端試圖使用'fetch'API向我創建的node.js Express API發出GET請求。 我啟用了CORS,並在這里瀏覽了許多問題,無法弄清楚為什么get請求不會在我的本地主機React應用程序上顯示數據。 在控制台日志中顯示它在控制台日志中顯示此...
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>
我使用郵遞員,每次都得到很好的要求。 這是郵遞員對我要提取的網址的回復...
{
"results": [
{
"name": "Jack",
"address": "NJ"
},
{
"name": "Steve",
"address": "NJ"
},
{
"name": "Denny",
"address": "NJ"
},
{
"name": "John",
"address": "NJ"
}
]
}
我想出了答案,我的Express應用正在將回復發送為...
res.status(200); // sends a status code
res.json({results}); // sends results received from sql
但我將其更改為此,現在可以使用...
res.status(200); // sends a status code
res.send(JSON.stringify(results)); // sends results recieved from sql
我仍然不太明白為什么它不能以json形式發送,而是以Express中的文本字符串形式發送的原因,React現在顯示數據。
只有狀態碼在200-299之間時, response.ok
為true
。 由於請求返回304,因此它將為false
。 這就是為什么重新加載頁面時不會顯示數據的原因。 有關從fetch
API response
的屬性,請參閱Mozilla文檔。
https://developer.mozilla.org/en-US/docs/Web/API/Response#Properties
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.