提问者:小点点

React原生错误:node_modules/axios/lib/core/createError. js:16:24 in createError


这是我写的

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/setle.js:19:6 in settings-…框架内部还有10个堆栈帧


共2个答案

匿名用户

问题出在url上。CodeSandbox显然阻止了超文本传输协议请求。更改为https

匿名用户

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

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

由于状态码无效(很可能是超文本标记语言401),响应被拒绝。检查您的api密钥是否仍然有效,或者在postman中测试您的URL。

编辑:下面是基于新URL的工作代码片段

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>