reactjs - 无法使用 axios.post 将图像发布到 imgur api
问题描述
我正在通过他们的 API 向 imgur 发布一张图片。这是 TS 上的 ReactJS 应用程序。
这里base64是图片的base64字符串,一般在50到100kb之间
const imgurApi = axios.create({
headers: {
'Authorization': 'Client-ID xxx'
}
})
export async function postImgurImage(base64: string, username: string, desc: string) {
try {
const data = {
"image": base64,
"title": username,
"description": desc
}
const res = await imgurApi.post('https://api.imgur.com/3/image', data)
if (res.status === 200) {
console.log(res.data);
return res.data
} else {
return `Error: ${res.statusText}`
}
} catch (err) {
console.log(err);
return err
}
}
这适用于邮递员,但是当我在浏览器上尝试此操作时,出现此错误
Error: Request failed with status code 429
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
编辑 1
这就是调用 postImgurImage 的方式。
const handleImg = (e: React.ChangeEvent < HTMLInputElement > ) => {
e.preventDefault();
if (e.target.files !== null) {
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
setPostImgPreview(reader.result ? .toString())
}
reader.readAsDataURL(file);
}
}
const handlePost = (e: React.MouseEvent < HTMLButtonElement, MouseEvent > ) => {
e.preventDefault();
const postNameVal = postname.current ? .value
const postContentVal = postcontent.current ? .value
if (postNameVal && postContentVal && postImgPreview) {
const base64 = postImgPreview.split(',')[1];
postImgurImage(base64, currentUser ? .username ? ? '', postContentVal).then(data => {
console.log(data);
})
}
}
<input type="file" name="post-image" id="post-image" accept="image/x-png,image/jpeg" onChange={e=> handleImg(e)} />
<button className="post-button" onClick={handlePost}>Post</button>
解决方案
推荐阅读
- android - 使用匕首时的警告:“@Component.Builder 具有不需要的模块或组件的设置器”
- python - Kivy关于希腊字符的Android字符串连接问题
- selenium - 在 Linux 中运行简单程序时出现 Selenium 错误
- javascript - 使用 Three.js 加载 600 万个三角形会使浏览器崩溃
- python - 如何避免在源代码中保留版本号?
- html - 如何在下拉菜单中调整或格式化块中的文本
- node.js - 在 Azure Pipelines 中运行 npm 版本脚本
- python - 通过 datetime.date 列表选择数据帧行(datetimeindex)
- javascript - 如何使用 img (即 href 链接)和单选按钮(值或 id)制作一个功能并转到下一页
- c# - BindingList 更新对象更改但忽略新的或删除的对象