使用提取的POST和GET API请求,无法获取数据

时间:2020-04-07 16:23:14

标签: javascript api fetch-api

我正在尝试使用以下网站: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)
}

非常感谢

1 个答案:

答案 0 :(得分:0)

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

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

我希望能帮上忙。