微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React - 使用 axios 将图像上传到 Imgur 返回 ERR_HTTP2_PROTOCOL_ERROR

如何解决React - 使用 axios 将图像上传到 Imgur 返回 ERR_HTTP2_PROTOCOL_ERROR

我正在尝试向 imgur API 发送 POST 请求 - 上传图片

我的 imgur 应用是公开的 - 只需要客户端 ID。

在运行时总是出现这个错误

错误:网络错误 在 createError (createError.js:16) 在 XMLHttpRequest.handleError (xhr.js:84) "POST https://api.imgur.com/3/image net::ERR_HTTP2_PROTOCOL_ERROR"

当我手动发送请求(使用 Postman)时它正在工作。 Postman success

设置:

  • WSL2 上的本地开发 - Ubuntu 20.04LTS
  • 反应
  • react-draft-wysiwyg

我的编辑:

<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);
      });
    },);
}

解决方法

我发现了这个问题。

参考:Imgur api responding with code 403 with server error 429

这个解决方案很完美。 Imgur 阻止来自本地主机的所有请求。

虽然由于 WSL 网络,您将无法访问 0.0.0.0 的服务器。

WSL Ubuntu 的解决方案:

hostname -I

在 package.json 旁边创建 .env 文件。

HOST=<output from hostname -I>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。