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:

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.

Leave a Reply