【问题标题】:How to make a fetch request to TinyURL?如何向 TinyURL 发出 fetch 请求?
【发布时间】:2021-04-07 17:35:14
【问题描述】:

我正在尝试向 tinyURL 发出获取请求,特别是发布请求,以缩短在我的网站上生成的 url。这是 tinyURL API

目前,我正在编写这样的代码,但它似乎没有返回短网址。

tinyurl 这个词似乎在链接中被禁止,所以所有链接 包含单词 tinyurl 已替换为“SHORT”

这是 tinyURL API https://SHORT.com/app/dev

import * as React from 'react'

interface tinyURlProps {   url: string } export const useTinyURL = ({ url }: tinyURlProps) => {   React.useEffect(() => {
    const apiURL = 'https://api.SHORT.com/create'
    const data = JSON.stringify({ url: url, domain: 'tiny.one' })

    const options = {
      method: 'POST',
      body: data,
      headers: {
        Authorization:
          'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    } as RequestInit

    fetch(apiURL, options)
      .then((response) => console.log(response))
      .then((error) => console.error(error))

    console.log('TinyUrl ran')   }, [url]) 
}

【问题讨论】:

  • 这是your other question 的旧版本吗?如果是这样,请删除这个。如果不是,请编辑其中一个问题,以便与另一个问题清楚地区分。
  • 这两个问题几乎是一样的,只问了5分钟?为什么?
  • it doesn't appear to be returning the short url 那么它在做什么呢?
  • 我的错误我认为这个版本没有发布它返回我输入的代码和消息和错误,我将删除其他
  • @IanKemp 这是我收到的回复imgur.com/VK4ISDg

标签: javascript reactjs typescript api fetch


【解决方案1】:

下面的 sn-p 似乎可以工作

const qs = selector => document.querySelector(selector);
let body = {
  url: `https://stackoverflow.com/questions/66991259/how-to-make-a-fetch-request-to-tinyurl`,
  domain: `tiny.one`
}

fetch(`https://api.tinyurl.com/create`, {
    method: `POST`,
    headers: {
      accept: `application/json`,
      authorization: `Bearer 2nLQGpsuegHP8l8J0Uq1TsVkCzP3un3T23uQ5YovVf5lvvGOucGmFOYRVj6L`,
      'content-type': `application/json`,
    },
    body: JSON.stringify(body)
  })
  .then(response => {
    if (response.status != 200) throw `There was a problem with the fetch operation. Status Code: ${response.status}`;
    return response.json()
  })
  .then(data => {
    qs(`#output>pre`).innerText = JSON.stringify(data, null, 3);
    qs(`#link`).href = data.data.tiny_url;
    qs(`#link`).innerText = data.data.tiny_url;
  })
  .catch(error => console.error(error));
body {
  font-family: calibri;
}
<p><a id="link" /></p>
<span id="output"><pre/></span>

【讨论】:

  • 你认为这可能与我使用 '' 而不是 ``有关吗?
  • 无论如何在 tinyurl api 调用中使用承载是什么...我只是不明白@Steve...
  • OpenAPI 规范中描述的http承载认证
猜你喜欢
  • 2017-01-28
  • 2015-05-28
  • 2019-01-25
  • 2017-06-02
  • 2022-01-22
  • 2020-04-02
  • 1970-01-01
  • 2019-05-25
相关资源
最近更新 更多