You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Wix Web应用调用API报Cannot read properties of undefined (reading 'orgao')如何解决

问题解决思路

首先Cannot read properties of undefined (reading 'orgao')报错的核心原因是:执行currencyInfo[0].orgao代码时,currencyInfo[0]为undefined,说明API返回的currencyInfo要么不是数组,要么是长度为0的空数组。

具体解决步骤

  • 第一步:增加返回值校验与错误捕获,同时打印日志确认接口返回内容
    前端代码修改为如下版本,可在Wix开发者控制台查看打印的API返回值,同时避免空值直接抛出报错:
    import {getCryptoCurrencyInfo} from 'backend/serviceModule';
    
    $w.onReady(function () {
        // Write your JavaScript here
    });
    
    export function button1_click(event, $w) {
            getCryptoCurrencyInfo($w('#currencyInput').value)
            .then(currencyInfo => {
                // 打印返回结果,确认返回结构与内容
                console.log("接口返回内容:", currencyInfo)
                // 非空判断避免报错
                if (Array.isArray(currencyInfo) && currencyInfo.length > 0) {
                    $w('#result').text = "Orgao: " + currencyInfo[0].orgao + "\n" 
                                            + "Evento: " + currencyInfo[0].evento + "\n"
                } else {
                    $w('#result').text = "未查询到对应数据"
                }
            })
            // 捕获请求层面的报错
            .catch(error => {
                console.error("请求出错:", error)
                $w('#result').text = "请求异常,请重试"
            })
    }
    
  • 第二步:修正后端接口的参数拼接逻辑
    你当前的后端代码写死了请求URL为固定值,完全没有用到传入的month参数,会导致不管前端输入什么值,都只会查询固定2018年1月的数据。如果需要动态传入月份查询,修改后端代码如下:
    import {fetch} from 'wix-fetch';
    
    export function getCryptoCurrencyInfo(month) {
        // 动态拼接月份参数到URL
        const url = `https://transparencia.tce.sp.gov.br/api/json/despesas/2018/${month}`;
        console.log("请求Url: " + url);
    
        return fetch(url, {method: 'get'})
            .then(response => {
                // 先判断请求是否成功
                if (!response.ok) {
                    throw new Error(`请求失败,状态码:${response.status}`)
                }
                return response.json()
            })
    }
    
  • 第三步:确认字段拼写与返回结构匹配
    通过第一步打印的接口返回内容,确认返回数据的字段名是否和你使用的orgao、evento完全一致,包括大小写、拼写是否存在差异。

内容的提问来源于stack exchange,提问作者user92837

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:45:05