Search code examples
reactjstypescriptaxioswysiwygdraftjs

React - upload an image to Imgur using axios returns ERR_HTTP2_PROTOCOL_ERROR


I'm trying to send POST request to Imgur API - to upload an image.

My Imgur App is public - only Client ID is required.

Always getting this error during runtime:

Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:84) "POST https://api.imgur.com/3/image net::ERR_HTTP2_PROTOCOL_ERROR"

It's working when I send the request manually (using Postman). Postman success

Setup:

  • Local Development on WSL2 - Ubuntu 20.04LTS
  • React
  • react-draft-wysiwyg

My editor:

<Editor
        editorState={content}
        onEditorStateChange={(e) => setContent(e)}
        wrapperClassName="demo-wrapper"
        editorClassName="demo-editor"
        toolbar={{
          image: {
            uploadCallback: uploadImageCallBack,
            alt: { present: true, mandatory: false },
          },
        }}
 />

Upload functions I've tried.

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

Attempt #2 - XHR Implementation from Documentation 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);
      });
    },
  );
}

Solution

  • I figured out this issue.

    Ref: Imgur api responding with code 403 with server error 429

    This solution worked out perfectly. Imgur blocks all requests from localhost.

    Although due to the WSL networking, you wont't be able to access server at 0.0.0.0.

    Solution for WSL Ubuntu:

    hostname -I
    

    Create .env file next to the package.json.

    HOST=<output from hostname -I>