【问题标题】:react native error: node_modules/axios/lib/core/createError.js:16:24 in createError反应原生错误:node_modules/axios/lib/core/createError.js:16:24 in createError
【发布时间】:2019-06-21 10:10:18
【问题描述】:

这个函数是我写的

fetchWeather(){
    axios.get(`http://api.openweathermap.org/data/2.5/forecast/daily?q=${this.state.city},uk&APPID=3a31a881817a041a63eac1c1bbbba705`)
    .then((response)=>{
      this.setState({report:response.data})
    }).catch((error)=>console.log(error))
  }

并得到这个错误:

node_modules/axios/lib/core/createError.js:16:24 in createError - node_modules/axios/lib/core/settle.js:19:6 解决 - ... 来自框架内部的另外 10 个堆栈帧

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    问题出在网址中。 CodeSandbox 显然会阻止 http 请求。改成https

    【讨论】:

      【解决方案2】:

      根据axiosGitHub代码(axios/lib/core/settle.js):

      reject(createError(
            'Request failed with status code ' + response.status,
            response.config,
            null,
            response.request,
            response
          ));
      

      响应因无效状态代码(很可能是 HTML 401)而被拒绝。检查您的 api 密钥是否仍然有效,或者在 postman 中测试您的 URL。

      编辑:下面是基于新 URL 的工作代码 sn-p

      class Hello extends React.Component {
      	constructor() {
        	super();
          this.state={
          	report: null,
          };
        }
      
        componentDidMount() {
        axios.get(`https://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=3a31a881817a041a63eac1c1bbbba705`)
        .then((response)=>{
        	this.setState({report:response.data});
          console.log(response.data);
        }).catch((error)=>console.log(error))
        }
        
        render() {
          return <div>Report: {JSON.stringify(this.state.report)}</div>;
        }
        
      }
      
      ReactDOM.render(
        <Hello />,
        document.getElementById('container')
      );
      <script src="https://unpkg.com/axios@0.16.1/dist/axios.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
      
      <div id="container">
      
      </div>

      【讨论】:

      • 我将 api 更改为:api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=3a31a881817a041a63eac1c1bbbba705 但我得到了同样的错误
      • @tiakocedrickdeco 您的新 api 密钥确实有效。我设法制作了一个有效的jsfiddle。确保您的网址设置为https://api.openweathermap.org/data/2.5/weather?q=London,uk&amp;APPID=3a31a881817a041a63eac1c1bbbba705
      猜你喜欢
      • 2020-10-21
      • 2021-04-12
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2021-07-09
      • 2021-10-20
      相关资源
      最近更新 更多