【问题标题】:axios does not work with while fetch doesaxios 不工作,而 fetch 工作
【发布时间】:2019-07-18 00:22:02
【问题描述】:

我想从 /{url} 获取数据(数组),我尝试了这段代码

// Fetch the list on first mount
componentDidMount() {
this.getList();
}

// Retrieves the list of items from the Express app
getList = () => {

fetch('/main')
.then(res => res.json())
.then(list => this.setState({ list }))
}

这工作正常,但后来我决定切换到 axios 并尝试了完全相同的代码

  // Fetch the list on first mount
componentDidMount() {
this.getList();
}

 // Retrieves the list of items from the Express app
 getList = () => {
 axios.get('/main')
.then(res=> res.json())
.then(list => this.setState({list}))

}

但它没有工作,并在这一行给了我错误:.then(res=> res.json()) 所以我不知道有什么问题,如果有人知道线索,如果你告诉我,我会很高兴

【问题讨论】:

    标签: node.js reactjs http axios fetch-api


    【解决方案1】:

    这是因为 axios 有不同的响应,而不是 res.json() 返回数据已经像:return res.data 或直接将其传递给状态类似

    getList = () => {
     axios.get('/main')
       .then(res=> this.setState({list: res.data}))
    

    【讨论】:

    • 它有效,但你能告诉我为什么吗? axios 有什么类型的响应?
    • 来自 axios 的响应是数据对象(包含大量附加数据的包装器),用于访问从 express 服务器提供的数据,您需要访问 taht 对象内部的 data,例如 response.data
    • 获取的响应是什么类型的实例?
    • 在此处查看 axios 文档 github.com/axios/axios 以及有关 fetch 的内容。 scotch.io/tutorials/… ...
    【解决方案2】:
    // Fetch the list on first mount
    componentDidMount() {
      this.getList();
    }
    
    // Retrieves the list of items from the Express app
    getList = () => {
     axios.get('/main')
     .then(res=> res.data)
     .then(list => this.setState({list}))
     .catch(error => this.setState({error: error.message}))
    }
    

    【讨论】:

      【解决方案3】:

      我会建议对您的设计进行一些更改,因为我在许多项目中都成功使用了 axios,这不是必需的,但它会有所帮助并且工作非常可靠:

      创建类似 api.js 的服务

      import axios from 'axios';
      
      export default axios.create({
        baseURL: `http://my.api.url/`
      });

      那你就可以这样使用了

      import API from '../Services/api'; // this is your service you created before
      
      LoadStats = async event => {
          try {
              var response = await API.get('api/targetroute');
              if (response.data != null) {
                  this.setState({
                      stats: {
                          mydata: response.data
                      }
                  });
                  console.log('Receiving result: '+JSON.stringify(response.data));
              }
          } catch (error) {
              console.log('ERROR: '+error)
          }
      }

      【讨论】:

      • 谢谢,我注意到您将代码修改为异步,但我认为 axios 已经与 Promise API 异步
      • axios 总是返回一个承诺,所以它总是异步的,这里的问题是如何在你的代码中处理承诺。有几种方法可以使用,使用订阅或使用 then /catch 处理承诺或使用异步装饰器都使用不同的软件设计处理承诺。我通常更喜欢使用来自 c# 的异步装饰器,并且我喜欢它允许的编程流程.. 当然,有时最好只订阅事件我个人认为 promise 链接 then / catch 是一个 nogo,因为它绝对是一团糟,但这是我个人的看法
      • 如果你问我不需要 baseUrl,(至少在我的情况下),因为我没有使用它,它仍然没有阻止跨域请求
      • 我喜欢它的清晰和美观,所以通过使用几个 api/路由/服务,我只需要更改基本 url 服务器更改等。通常每个 api 有多个路由可以使用,所以总体上所有路由都有一个基本网址当然这是个人设计的事情,按照你喜欢的方式去做:) 你说的......仍然没有阻止 CORS 是什么意思?
      • 我也支持你和你的评论,也许 Stackoverflow 有问题
      猜你喜欢
      • 2022-01-24
      • 2021-07-04
      • 2017-06-12
      • 2018-11-07
      • 2014-02-14
      • 1970-01-01
      • 2018-12-24
      • 2019-02-05
      • 2018-04-27
      相关资源
      最近更新 更多