在位置 0 的 JSON 中获取 API React Js 意外标记 <

Fetch API React Js Unexpected token < in JSON at position 0

当我从名为 url 的状态传递 url 提取 API 时,我从提取 api 中收到此错误。但是当我将 url 更改为 'api/provinsi' 之类的文本时,我没有收到任何错误

Error fetching data: SyntaxError: Unexpected token < in JSON at position 0

   useEffect(() => {
        async function fetchMyAPI() {
            await fetch(url, {
                method: 'GET'
            }).then(response => {
                if(!response.ok) {
                    throw new Error(response.statusText);
                }
                return response.json();
            })
            .then(response => {
                if(response.Response === 'False') {
                    throw new Error(response.Error);
                }
                setData(response.data);
            }).catch(error => {
                console.log("Error fetching data: ", error);
            });
        }
        fetchMyAPI();
    }, []);

这就是我设置 url 状态的方式:

  useEffect(() => {
        if(idDaerah==1){
            setColumn(['no', 'nama', 'aksi']);
            setUrl('/api/provinsi');
        } else if(idDaerah==2) {
            setColumn(['no', 'nama', 'provinsi_id', 'aksi']);
            setUrl('/api/kabupaten');
        } else if(idDaerah==3) {
            setColumn(['no', 'nama', 'kabupaten_id', 'aksi']);
            setUrl('/api/kecamatan');
        } else {
            setColumn(['no', 'nama', 'kecamatan_id', 'aksi']);
            setUrl('/api/desa');
        }
    }, []);

因为两个useEffect同时运行,fetch函数第一次接收url作为empty string,所以需要添加url作为依赖.

useEffect(() => {
        async function fetchMyAPI() {
            await fetch(url, {
                method: 'GET'
            }).then(response => {
                if(!response.ok) {
                    throw new Error(response.statusText);
                }
                return response.json();
            })
            .then(response => {
                if(response.Response === 'False') {
                    throw new Error(response.Error);
                }
                setData(response.data);
            }).catch(error => {
                console.log("Error fetching data: ", error);
            });
        }
       if(url !== ''){ //check if url is set i.e not an empty string
        fetchMyAPI();
      }
    }, [url]); //add dependency, when url change then call api

您可以提供默认值 url,例如:

const [url, setUrl] = useState('/api/provinsi');