根據建議進行編輯 嘗試使用 fetch 進行編輯,現在我得到了


我正在嘗試在一個簡單的 react 應用程式中從 gnews.io/api 獲取資料。我正在學習 React,解決方案可能很簡單,但我被困在這里,無法找出問題所在,我不斷收到此錯誤
fetch-jsonp.js:88 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://gnews.io/api/v4/top-headlines?country=us&token=myapi with MIME type application/json.
有趣的是,如果我復制此 urlhttps://gnews.io/api/v4/top-headlines?country=us&token=MYAPI&callback=jsonp_1642257010280_37644
并將其粘貼到瀏覽器中,我會得到所需的回應。
非常感謝任何形式的幫助
這是進行此 api 呼叫的 useEffect 函式
React.useEffect(()=> {
async function getNewsdata(country){
try {
let url = `https://www.gnews.io/api/v4/top-headlines?country=pk&token=${API2}`
let response = await fetchJsonp(url)
let result = await response.json()
console.log("News Data:", result)
} catch (error) {
console.log("error loading news data: ", error)
}
}
getNewsdata(props.country.trim())
},[])
uj5u.com熱心網友回復:
如今,訴諸JSONP已不受歡迎。有更安全的替代品,例如 CORS。因為回應的內容型別是application/json,所以無論如何使用 JSONP 都不起作用,因為它會導致Chrome 的 CORB 功能啟動。
為什么不嘗試解決您似乎遇到的任何 CORS 問題?如果您使用的 API 沒有針對 CORS 進行配置,我會感到非常驚訝……隨便檢查一下他們的檔案就會發現您使用了錯誤的域,www.gnews.io而不是gnews.io. 前者重定向到后者,但沒有為 CORS 配置,這就解釋了你的 CORS 麻煩。
一旦您使用了正確的域 ( gnews.io),您所有的 CORS 問題都將迎刃而解。而且由于不再需要使用 JSONP 之類的骯臟技巧,因此您可以使用良好的舊可靠fetch工具,而不是某些第三方工具。
React.useEffect(()=> {
async function getNewsdata(country){
try {
let url = `https://gnews.io/api/v4/top-headlines?country=pk&token=${API2}` // gnews.io, not www.gnews.io
let response = await fetch(url) // fetch, not fetchJsonp
let result = await response.json()
console.log("News Data:", result)
} catch (error) {
console.log("error loading news data: ", error)
}
}
getNewsdata(props.country.trim())
},[])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411664.html
標籤:
