首页 > 解决方案 > POST 和 GET API 请求使用 fetch,无法获取数据

问题描述

我正在尝试使用这个网站:https : //rel.ink/,在我的 webapp 中实现链接缩短器,我可以成功发布请求,但我得到的是同一个对象,而不是缩短的版本。我知道这是基本的东西,但我无法理解它。该网站声明我需要通过 GET 请求发送更多信息,但 GET 请求不应包含正文,是吗?

这是我的代码:

async function fetchNewLink() {

  let newLinkJson = await postLink(input.value)

  let newLink = await getShortLink(newLinkJson)
  console.log(newLink)
}

function postLink(input) {
  return fetch('https://rel.ink/api/links/', {
      method: 'POST',
      body: JSON.stringify({
        url: input
      }),
      headers: {
        "Content-type": "application/json"
      }
    })
    .then(response => response.json())
    .then(json => json)
}

function getShortLink(response) {
  return fetch('https://rel.ink/api/links/' + response.hashid)
    .then(result => result.json())
    .then(newLink => newLink)
}

非常感谢

标签: javascriptapifetch-api

解决方案


如果您要获取的是链接的缩短版本,则 API 不会在您发出请求时完全返回该链接。但是,您所需要的只是hashid它返回。缩短的链接是主网站的 url( https://rel.ink) 与hashid.

因此,如果 API在您发出 POST 请求时返回,则缩短的链接将nJzb3nhashidhttps://rel.ink/nJzb3n

我希望这会有所帮助。


推荐阅读