【问题标题】:Can't get response of GET request AxiosGET 请求 Axios 无法得到响应
【发布时间】:2019-03-19 19:13:20
【问题描述】:

我正在从 OpenWeather API 调用 GET 请求,如下所示:

const config = {
            headers: {
              accept: 'application/json',
            },
            data: {},
          };
        const url = 'http://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b6907d289e10d714a6e88b30761fae22';
        Axios.get(url, config).then((response) => {
            console.log(response);
        }).catch((e) => {
            Alert.alert('error', `${e}`);
            });

但是 .then() 没有被调用,大约 15 秒后它抛出异常并显示 catch 警报(说 Network Error 而其他 API 调用正在工作,因此网络错误并不是真正的问题)。

该网址在浏览器中有效,但 Axios 无法进行该调用。 有人知道发生了什么吗?

【问题讨论】:

    标签: javascript android ios react-native axios


    【解决方案1】:

    确保您在顶部需要 NPM 包:

    对于节点/反应:

    const axios = require('axios');
    
    import axios from 'axios';

    您提供的代码对我有用。我只是安装了 axios,将其导入,并在您的示例中小写了“axios”,然后我得到了气象服务的响应。

    我收到了以下 JSON 数据响应(以及其他一些内容):

     data:
       { cod: '200',
         message: 0.0036,
         cnt: 40,
         list:
          [ [Object],
            ...
            [Object],
            [Object] ],
         city:
          { id: 524901, name: 'Moscow', coord: [Object], country: 'none' } } }

    【讨论】:

      【解决方案2】:

      使用async/await。它使您的代码更易于阅读并避免回调地狱。

      import axios from 'axios';
      
      const fetchData = async () => {
        const config = {
          headers: {
            accept: 'application/json',
          },
         data: {},
        };
      
        const url = 'http://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b6907d289e10d714a6e88b30761fae22';
      
        const response = await axios.get(url, config);
        console.log(response);
      }
      

      【讨论】:

        猜你喜欢
        • 2022-01-08
        • 2021-08-01
        • 2021-11-17
        • 2020-09-01
        • 2016-01-24
        • 1970-01-01
        • 2021-05-03
        • 2020-07-07
        • 2021-04-15
        相关资源
        最近更新 更多