問(wèn)題
今天再寫(xiě)一個(gè)很簡(jiǎn)單的代碼,是調(diào)用一段API的代碼们豌,類似如下的:
componentDidMount() {
fetch("api.openweathermap.org/data/2.5/weather?q=London&units=Metric")
.then(response => response.json())
.then(responseData => {
this.setState({
temp: responseData.main.temp,
desc: responseData.weather[0].description,
icon: responseData.weather[0].icon,
loading: false
})
})
.catch(err => console.log(err));
}
我在本地調(diào)用,postman測(cè)試都沒(méi)問(wèn)題浅妆,然后跑程序的時(shí)候望迎,就每次報(bào)這個(gè)錯(cuò)誤,后來(lái)才發(fā)現(xiàn)狂打,這個(gè)fetch里面擂煞,必須要在前面加上我們的http,把程序改成如下就可以了趴乡。
解決方法:
fetch("http://api.openweathermap.org/data/2.5/weather?q=London&units=Metric")
原因是如果是地址不正確对省,他就不會(huì)解析出來(lái)我們的json蝗拿,而是一個(gè)http的respose,第一個(gè)字符就是<,所以我們想在后面使用我們的對(duì)象就不對(duì)了蒿涎。