简体   繁体   English

错误消息:SyntaxError: Unexpected token < in JSON at position 0

[英]Error message : SyntaxError: Unexpected token < in JSON at position 0

i was trying to fetch a data for a project but everytime i'm converting the fetch data to json it returns me我试图为一个项目获取数据但每次我将获取数据转换为 json 它都会返回我

SyntaxError: Unexpected token < in JSON at position 0 SyntaxError: 位置 0 处的 JSON 中的意外标记 <

i don't understand why it's showing me this我不明白为什么它给我看这个

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])

please visit the API page from the URL & see if there's an issue with the data.请从 URL 访问 API 页面并查看数据是否存在问题。 the data is not fetching.数据未获取。 what's the issue?有什么问题?

Link 关联

Doing正在做

fetch('www.thecocktaildb.com/')

will fetch not that website, but that path relative to the current path .不会获取网站,而是获取相对于当前路径的路径 For example, doing so here on Stack Overflow results in the URL being fetched being例如,在 Stack Overflow 上执行此操作会导致获取的 URL 为

https://stackoverflow.com/questions/72914244/www.thecocktaildb.com/

which, of course, doesn't exist - and presumably that URL doesn't exist on your site either.当然,它不存在 - 并且大概该 URL 也不存在于您的网站上。

Use the full path.使用完整路径。

const url = 'https://www.thecocktaildb.com/api/json/v1/1/search.php?s='

I'd also recommend only calling the API when searchTerm isn't empty, and perhaps add a debounce of a few hundred milliseconds so as not to call it too often and to keep the client from being blocked.我还建议仅在searchTerm不为空时调用 API,并且可能添加几百毫秒的去抖动,以免过于频繁地调用它并防止客户端被阻塞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM