Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JSON post request isn't working (React.js)

Here’s my "sendRequest" function that is called when the "Upload" button is clicked:

async function sendRequest() {
  let encodedString = '';
  var reader = new FileReader(); 
  reader.onload = (function(selectedFile) {
    return function(e) {
      var binaryData = e.target.result;
      var base64String = btoa(String(binaryData));
      encodedString = base64String;
    };
  })(selectedFile);
  reader.readAsBinaryString(selectedFile);
  try {
    const response = await fetch('http://0.0.0.0:8000/api/convert_pdf/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({pdf_encoded: encodedString})
    }).then(response => response.json())  // convert to json
      .then(json => console.log(json))    //print data to console
      .catch(err => console.log('Request Failed', err)); // Catch errors;
  } catch(error) {
    console.log('error: ' + error);
  }
  
}

It returns an 500:JSON.parse: unexpected character at line 1 column 1 of the JSON data

However, the following python code that makes a POST request to the same API works just fine:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import argparse
import base64
import json
from io import BytesIO

import requests

url = "http://0.0.0.0:8000/api/convert_pdf/"

headers = {
    "Content-Type": "application/json",  # Specify the content type as a JSON payload
}

filepath = 'perfect_cv/generator/scripts/file.pdf'

with open(filepath, "rb") as fh:
    encoded = base64.b64encode(fh.read()).decode("utf-8")

print(type({"pdf_encoded": encoded}))

response = requests.post(url, json={"pdf_encoded": encoded}, headers=headers)

if response.status_code == requests.codes.ok:
    print("PDF uploaded and converted successfully")
else:
    print("Error uploading PDF:", response.status_code)

>Solution :

First thing: FileReader works asynchronously. Which means that your fetch will happen before the file is read:

  reader.readAsBinaryString(selectedFile); // reader starts reading file,
                                           // will finish in a few milliseconds

  try { // but this line is executed right now
    const response = await fetch('http://0.0.0.0:8000/api/convert_pdf/', {

You need to put things that happen after the file is read in onload callback.

Also, try to avoid mixing await with .then(). You don’t need both.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading