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

使用Axios调用Wiktionary API适配wiktionary-parser遇类型错误求解

Axios调用Wiktionary接口适配wiktionary-parser时数据结构错误问题

问题背景

首次使用Axios进行接口请求,开发React Native词典应用,调用Wiktionary接口的核心代码如下:

let url = "https://en.wiktionary.org/w/api.php?format=json&action=query&titles={word}&rvprop=content&prop=revisions&redirects=1&callback=?".replace("{word}", word);
...
axios({
  method: 'get',
  url: url,
}).then((response) => {
  var results = {
    title: "",
    definitions: [],
    examples: []
  }
  ....
  let data = response.data;
  ...

接口请求本身可行,但尝试适配wiktionary-parser时出现错误。

错误详情

执行以下校验代码时:

if(!data || !data.query || !data.query.pages || data.query.pages[-1]) {
    return callback({});
}

抛出错误:

TypeError: Cannot read property 'pages' of undefined

推测Axios返回的数据结构与原wiktionary-parser使用$.getJSON获取的数据结构不一致,尝试过用JSON.stringify(response.data)和JSON.parse(response.data)处理,问题仍未解决。

完整请求代码

function getENWiktionaryInfo(word, wordLanguage, callback) {
  //  getJSON("https://en.wiktionary.org/w/api.php?format=json&action=query&titles={word}&rvprop=content&prop=revisions&redirects=1&callback=?".replace("{word}", word), function (data) {
  //        $.getJSON("https://en.wiktionary.org/wiki/abdico#Latin", function (data) {
  let url = "https://en.wiktionary.org/w/api.php?format=json&action=query&titles={word}&rvprop=content&prop=revisions&redirects=1&callback=?".replace("{word}", word);
  console.log("getENWiktionaryInfo " + url);

  axios({
    method: 'get',
    url: url,
  }).then((response) => {
    var results = {
      title: "",
      definitions: [],
      examples: []
    }

    let data = response.data;
    console.log("DATA "+data);
    const jsonObj= JSON.stringify(response.data)
    //let data = jsonObj;
    var title, content;

    if (!data || !data.query || !data.query.pages || data.query.pages[-1]) {
      return callback({});
    }

    callback(results);
  });
}

请求拉丁语单词“res”的URL示例:

https://en.wiktionary.org/w/api.php?format=json&action=query&titles=res&rvprop=content&prop=revisions&redirects=1&callback=?

求助

请问代码中哪里操作有误?如何解决该问题?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:35:22