已解决的请求承诺错误:即使在React.js中请求未失败,“ TypeError:提取失败”

时间:2020-10-27 19:09:35

标签: reactjs request cors request-promise

我正在尝试在React.js应用程序中获取API。但是,即使请求成功,我的React应用程序也会返回错误“ TypeError:无法提取”。这是我的代码:

let tree = {
    id: 1,
    name: "tree1",
    children: [
      {
        id: 2,
        name: "tree2",
        children: [
          {
            id: 4,
            name: "tree4",
            children: [
              {
                id: 6,
                name: "tree6"
              },
              {
                id: 7,
                name: "tree7"
              }
            ]
          },
          {
            id: 5,
            name: "tree5"
          }
        ]
      },
      {
        id: 3,
        name: "tree3"
      }
    ]
  };
  
const findById = (id, obj, path = 'tree') => {
    if (obj.id === id) return [obj, path];
    else if (obj.children) {
        for (let i = 0; i < obj.children.length; i++) {
            const [child, p] = findById(id, obj.children[i], path + `.children[${i}]`);
            if (child) {
                return [child, p];
            }
        }
    }
    return [null, path];
}

console.log(findById(7, tree, 'tree'));

我认为这是因为我从本地服务器-http:// localhost:3000发送了一个请求。我也尝试使用标头“ no cors”来获取,但是它对我不起作用。这也是来自控制台的错误:

function shorten(longlink) {
  const apikey = "**********";
  const protocol = "http";
  let data;

  const submitlink = `https://cutt.ly/api/api.php?key=${apikey}&short=${protocol}://${longlink}`;

  rp(submitlink).then(body => {
    data = JSON.parse(body);
  })

  console.log(data);
  }

我该如何解决?

0 个答案:

没有答案