问题描述
我正在尝试将POST请求发送到Imgur API-上传图像.
I'm trying to send POST request to Imgur API - to upload an image.
我的Imgur应用程序是公开的-仅需要客户端ID.
My Imgur App is public - only Client ID is required.
在运行时始终出现此错误:
Always getting this error during runtime:
当我手动发送请求(使用邮递员)时,它可以正常工作.邮递员成功
It's working when I send the request manually (using Postman).Postman success
设置:
- 在WSL2上进行本地开发-Ubuntu 20.04LTS
- 反应
- 反应草案所见即所得
我的编辑器:
<Editor
editorState={content}
onEditorStateChange={(e) => setContent(e)}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
toolbar={{
image: {
uploadCallback: uploadImageCallBack,
alt: { present: true, mandatory: false },
},
}}
/>
上传我尝试过的功能.
尝试#1-axios实现
Attempt #1 - axios implementation
function uploadImageCallBack(file) {
return new Promise<void>((resolve, reject) => {
const data = new FormData();
data.append("image", file);
const config = {
headers: {
Authorization: "Client-ID xxx",
},
};
axios.post("https://api.imgur.com/3/image", data, config).then((res) => {
console.log(res);
resolve()
}).catch(err => {
console.log(err)
reject()
});
});
}
尝试#2-文档中的XHR实施 https://github.com/jpuri/react-draft-wysiwyg/blob/master/stories/ImageUpload/index.js
Attempt #2 - XHR Implementation from Documentationhttps://github.com/jpuri/react-draft-wysiwyg/blob/master/stories/ImageUpload/index.js
function uploadImageCallBack(file) {
return new Promise(
(resolve, reject) => {
const xhr = new XMLHttpRequest(); // eslint-disable-line no-undef
xhr.open('POST', 'https://api.imgur.com/3/image');
xhr.setRequestHeader('Authorization', 'Client-ID xxx');
const data = new FormData(); // eslint-disable-line no-undef
data.append('image', file);
xhr.send(data);
xhr.addEventListener('load', () => {
const response = JSON.parse(xhr.responseText);
resolve(response);
});
xhr.addEventListener('error', () => {
const error = JSON.parse(xhr.responseText);
reject(error);
});
},
);
}
推荐答案
我发现了这个问题.
参考: Imgur api响应代码为403,服务器错误429
此解决方案效果理想.Imgur阻止来自本地主机的所有请求.
This solution worked out perfectly.Imgur blocks all requests from localhost.
尽管由于WSL网络的缘故,您将无法以0.0.0.0访问服务器.
Although due to the WSL networking, you wont't be able to access server at 0.0.0.0.
WSL Ubuntu的解决方案:
Solution for WSL Ubuntu:
hostname -I
在package.json旁边创建.env文件.
Create .env file next to the package.json.
HOST=<output from hostname -I>
这篇关于反应-使用axios将图像上传到Imgur返回ERR_HTTP2_PROTOCOL_ERROR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!