[英]Error message : SyntaxError: Unexpected token < in JSON at position 0
我試圖為一個項目獲取數據但每次我將獲取數據轉換為 json 它都會返回我
SyntaxError: 位置 0 處的 JSON 中的意外標記 <
我不明白為什么它給我看這個
import React,{useContext,useState,useEffect} from 'react'
const url = 'www.thecocktaildb.com/api/json/v1/1/search.php?s='
export default function AppProvider({children}) {
const [loading,setLoading] = useState(true)
const [searchTerm,setSearchTerm] = useState('a')
//set it as 'a' for suggestion at search bar at beginning.
const [cocktails,setCocktails] = useState([])
const fetchUrl = async ()=>{
setLoading(true)
try {
const response = await fetch(`${url}${searchTerm}`)
//(${url}${searchterm} helps me to fetch data at first with names that starts with 'a' for suggestion///
const data = await response.json()
setLoading(false)
} catch (error) {
console.log(error)
}
}
useEffect(()=>{
fetchUrl()
},[searchTerm])
請從 URL 訪問 API 頁面並查看數據是否存在問題。 數據未獲取。 有什么問題?
正在做
fetch('www.thecocktaildb.com/')
不會獲取該網站,而是獲取相對於當前路徑的路徑。 例如,在 Stack Overflow 上執行此操作會導致獲取的 URL 為
https://stackoverflow.com/questions/72914244/www.thecocktaildb.com/
當然,它不存在 - 並且大概該 URL 也不存在於您的網站上。
使用完整路徑。
const url = 'https://www.thecocktaildb.com/api/json/v1/1/search.php?s='
我還建議僅在searchTerm
不為空時調用 API,並且可能添加幾百毫秒的去抖動,以免過於頻繁地調用它並防止客戶端被阻塞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.