POST 和 GET API 请求使用 fetch,无法获取数据
POST and GET API Request using fetch, cannot get the data
我正在尝试使用这个网站:https://rel.ink/,
在我的网络应用程序中实施 link-shortener,
我可以成功 POST 一个请求,但我得到的是同一个对象,而不是缩短的版本。
我知道这是基本的东西,但我无法理解它。
该网站声明我需要通过我的 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)
}
非常感谢
如果您要获取的是 link 的缩短版本,则 API 与您发出请求时 return 并不完全相同。但是,您只需要 hashid
和 return 即可。缩短的 link 是主网站的 url(https://rel.ink
) 与 hashid
.
连接而成
因此,如果 API returns nJzb3n
作为 hashid
当您发出 POST 请求时,缩短的 link 将成为 https://rel.ink/nJzb3n
希望对您有所帮助。
我正在尝试使用这个网站:https://rel.ink/, 在我的网络应用程序中实施 link-shortener, 我可以成功 POST 一个请求,但我得到的是同一个对象,而不是缩短的版本。 我知道这是基本的东西,但我无法理解它。 该网站声明我需要通过我的 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)
}
非常感谢
如果您要获取的是 link 的缩短版本,则 API 与您发出请求时 return 并不完全相同。但是,您只需要 hashid
和 return 即可。缩短的 link 是主网站的 url(https://rel.ink
) 与 hashid
.
因此,如果 API returns nJzb3n
作为 hashid
当您发出 POST 请求时,缩短的 link 将成为 https://rel.ink/nJzb3n
希望对您有所帮助。