我写了这个 fonction
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 in settle - ...来自框架内部的 10 多个堆栈帧
问题出在网址上。CodeSandbox显然阻止了http
请求。更改为https
根据 axios GitHub 代码 (axios/lib/core/settle.js):
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
由于状态代码无效(很可能是 HTML 401),响应被拒绝。检查您的 api 密钥是否仍然有效,或在邮递员中测试您的 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>