Javascript 如何在react中调试简单的API

Javascript 如何在react中调试简单的API,javascript,node.js,reactjs,api,Javascript,Node.js,Reactjs,Api,URL localhost上有一个简单的API:3001/swags和一些项目,现在我想在一个非常简单的REACT应用程序中显示它们 这是我的REACT应用程序: import React, { Component } from 'react'; class App extends Component { constructor(props) { super(props); this.state = { swags: null }; } co

URL localhost上有一个简单的API:3001/swags和一些项目,现在我想在一个非常简单的REACT应用程序中显示它们

这是我的REACT应用程序:

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      swags: null
    };
  }

  componentDidMount() {
    fetch('http://localhost:3001/swags')
      .then(response => response.json())
      .then(data => this.setState({ swags: data }));
  }

  render() {        
    return (
      <div><pre>{JSON.stringify(this.state, null, 2) }</pre></div>
    );
  }
}

export default App;
邮递员在此URL下显示此输出


有人能解释为什么我的简单应用程序的输出是空对象吗?

根据您的代码。页面将首先使用
swags:null呈现,然后调用
http://localhost:3001/swags
。如果您的请求成功,您将在屏幕上得到响应。如果屏幕上的值没有更改,则表示API调用中出现了错误。您可以添加一个
catch
块,也可以在final中打印值,然后检查是否一切正常


按照你的代码。页面将首先使用
swags:null呈现,然后调用
http://localhost:3001/swags
。如果您的请求成功,您将在屏幕上得到响应。如果屏幕上的值没有更改,则表示API调用中出现了错误。您可以添加一个
catch
块,也可以在final中打印值,然后检查是否一切正常


尝试打印
then()
处理程序中的控制台数据,以确保实际获取了数据。可能会将构造函数中swag的值设置为空数组[]
this.state={swags:[]}在浏览器中调试开始。使用开发人员工具。看看控制台。有错误吗?查看网络选项卡,请求和响应是否与您期望的完全一致?Dollars to doughnuts表示这是另一个重复的,即在
then()
处理程序中尝试打印到控制台数据,以确保实际获取数据。可能会将构造函数中swag的值设置为空数组[]
this.state={swags:[]}在浏览器中调试开始。使用开发人员工具。看看控制台。有错误吗?查看网络选项卡,请求和响应是否与您期望的完全一致?Dollars to doughnuts说这是这个答案的另一个副本很有帮助,通过控制台输出我可以调试API调用,并看到错误只是一个限制问题。这个答案很有帮助,通过控制台输出我可以调试API调用,并看到错误只是一个限制问题。
{
  "swags": null
}
[
    {
        "id": 1,
        "title": "Item 1",
        "description": "Lorem ipsum dolor sit amet"
    },
    {
        "id": 2,
        "title": "Item 2",
        "description": "sed diam nonumy eirmod tempor"
    },
    {
        "id": 3,
        "title": "Item 3",
        "description": "takimata sanctus est Lorem ipsum dolo"
    }
]
fetch('http://localhost:3001/swags')
.then(response => response.json())
.then(data => {
    console.log(data) // Check the value of data in console
    this.setState({ swags: data })
})
.catch(err => {
    console.log(data) // Check if error in console
    this.setState({ swags: 'API Failed' })
})