【问题标题】:Fetch API React Js Unexpected token < in JSON at position 0获取 API React Js Unexpected token < in JSON at position 0
【发布时间】:2021-11-06 09:09:09
【问题描述】:

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

获取数据时出错:SyntaxError: Unexpected token

   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();
    }, []);

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

  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');
        }
    }, []);

【问题讨论】:

  • 您的响应应该是格式错误的 json
  • url 的初始值是多少?您可能遇到过时关闭的问题,因为 url 未在 useEffect 钩子的依赖数组中指定。
  • @Yousaf 我将多次使用具有不同获取 url 的组件。我应该创建另一个函数并将 url 作为参数传递吗?
  • 听起来响应不是 JSON。那么响应是什么?在浏览器的调试工具中,检查网络选项卡。提出了什么要求?回应是什么?它们与您的预期有何不同?
  • @David 这是一个对象。查看 bakar_dev 的答案

标签: reactjs fetch-api use-effect


【解决方案1】:

因为两个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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-14
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2021-06-06
    • 2021-09-30
    相关资源
    最近更新 更多