我写了这个函数
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))
}
Run Code Online (Sandbox Code Playgroud)
并得到这个错误:
createError 中的 node_modules/axios/lib/core/createError.js:16:24 - Settle 中的 node_modules/axios/lib/core/settle.js:19:6 - ...来自框架内部的另外 10 个堆栈帧
根据axios GitHub代码(axios/lib/core/settle.js):
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
Run Code Online (Sandbox Code Playgroud)
由于状态代码无效(很可能是 HTML 401),响应被拒绝。检查您的 api 密钥是否仍然有效,或在 postman 中测试您的 URL。
编辑:下面是基于新 URL 的工作代码片段
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
Run Code Online (Sandbox Code Playgroud)
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')
);Run Code Online (Sandbox Code Playgroud)