首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何向TinyURL发出获取请求?

如何向TinyURL发出获取请求?
EN

Stack Overflow用户
提问于 2021-04-07 17:35:14
回答 1查看 440关注 0票数 0

我试图发出一个获取请求,特别是对tinyURL的post请求,以缩短在我的站点上生成的url。以下是tinyURL API

目前,我正在这样写我的代码,但是它似乎没有返回简短的url。

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

下面是tinyURL API https://SHORT.com/app/dev

代码语言:javascript
复制
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]) 
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-07 18:28:01

下面的片段似乎很有效

代码语言:javascript
复制
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));
代码语言:javascript
复制
body {
  font-family: calibri;
}
代码语言:javascript
复制
<p><a id="link" /></p>
<span id="output"><pre/></span>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66991259

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档