如何获取并返回静态geojson



我正试图通过fetch调用访问一个原始的geojson,并将其存储在状态中。这只是暂时的,不是生产规模的应用。不过我不确定哪里出了问题。我的代码如下:

fetchData = async () => {
let data = await
fetch(
"https://raw.githubusercontent.com/timwis/leaflet-choropleth/gh-pages/examples/basic/crimes_by_district.geojson"
)
.then((response) => response.json())
.then((geojson) => {
console.log("my_data: ", geojson)
return geojson
})
console.log("my_data: ", geojson)
this.setState({ geojson: data })
return data
}

我得到以下信息:

my_data:  {type: "FeatureCollection", features: Array(22), crs: {…}}
App.js:218 my_data:  /static/media/hh_2020112300_2020120623_Saturday_02.d9141b26.geojson

我认为问题是console.log("my_data: ", geojson)(第二个(执行时geojson超出了作用域。第二个控制台日志不应该是console.log("data: ", data)吗?

试试这个

let data = await fetch(
"https://raw.githubusercontent.com/timwis/leaflet-choropleth/gh-pages/examples/basic/crimes_by_district.geojson",
{
headers: {
accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-language": "en-US,en;q=0.9,ar;q=0.8,bn;q=0.7",
"cache-control": "max-age=0",
"if-none-match":
'W/"8c50b5f19d835c2097cf05ef5967bdf5531f37aaaed918b17479328f69aa7309"',
"sec-ch-ua":
'"Google Chrome";v="87", " Not;A Brand";v="99", "Chromium";v="87"',
"sec-ch-ua-mobile": "?0",
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "none",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
},
referrerPolicy: "strict-origin-when-cross-origin",
body: null,
method: "GET",
mode: "cors",
credentials: "omit",
}
);

最新更新