我正在尝试向 Imgur API 发送 POST 请求 - 上传图像。
我的 Imgur 应用程序是公开的 - 只需要客户端 ID。
在运行时总是收到此错误:
错误:XMLHttpRequest.handleError (xhr.js:84) 处的 createError (createError.js:16) 网络错误“POST https://api.imgur.com/3/image net::ERR_HTTP2_PROTOCOL_ERROR”
当我手动发送请求(使用邮递员)时,它正在工作。 邮差成功
设置:
- WSL2 上的本地开发 - Ubuntu 20.04LTS
- react
- react草稿所见即所得
我的编辑:
<Editor
editorState={content}
onEditorStateChange={(e) => setContent(e)}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
toolbar={{
image: {
uploadCallback: uploadImageCallBack,
alt: { present: true, mandatory: false },
},
}}
/>
上传功能我试过了。
尝试 #1 - axios 实现
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
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);
});
},
);
}