javascript - 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)
}
非常感谢
解决方案
如果您要获取的是链接的缩短版本,则 API 不会在您发出请求时完全返回该链接。但是,您所需要的只是hashid
它返回。缩短的链接是主网站的 url( https://rel.ink
) 与hashid
.
因此,如果 API在您发出 POST 请求时返回,则缩短的链接将nJzb3n
是hashid
https://rel.ink/nJzb3n
我希望这会有所帮助。
推荐阅读
- ios - SwiftUI 自定义模态视图过渡滞后
- javascript - 尝试将汉堡菜单图标固定在左侧,并且在汉堡菜单打开时不移动
- android - fragment recyclerview 出现此错误 E/RecyclerView: No adapter attach; 跳过布局
- java - 为什么我会收到“找不到合适的驱动程序”错误?
- reactjs - 在 li 标签内反应多个标签
- image - “无法上传大于 5mb 的图像” - 使用图像魔法将图像转换为 5mg 的最大尺寸
- c++ - C++ 构造函数中的枚举
- java - 抽屉隐藏在自定义视图中
- xml - 尝试使用 JAXB 将 Double 转换为 XML 转换时如何避免指数(科学)字符串
- r - 为什么 group_by + 汇总数千个观察结果会产生 1x1 的数据框?