0

Hi I keep getting the error SyntaxError: Unexpected token < in JSON at position 0 I would appreciate your help in finding out what I am doing wrong. My code is as follow:

  var rnd = document.getElementById("rnd");
  var sendThis = rnd.textContent;
  console.log(sendThis);
  var URL = "";
  const csrftoken = getCookie("csrftoken");

  window.onload = () => {
    sendit();
  };

  function sendit() {
    console.log("sending");
    fetch(URL, {
      method: "POST",
      credentials: "same-origin",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "X-Requested-With": "XMLHttpRequest",
        "X-CSRFToken": csrftoken,
      },
      body: JSON.stringify({
        'rndValue': 'Test value',
      }),
    })
      .then((response) => {
        return response.json();
      })
      .then((messages) => {
        console.log("messages");
      })
    .catch(error => {
      console.log(error);
    }
   );

    console.log("Sent");
  }
stressedkid
  • 45
  • 1
  • 7
  • It says the error is in the JSON at position 0, but the code you've provided isn't the JSON you're trying to parse! – Quentin Nov 02 '20 at 09:42
  • 2
    You're *most likely* receiving HTML back. And if it's HTML, it's *most likely* an HTML page. So, check what the actual response is, instead of parsing it as JSON - it will likely suggest what's wrong. It might be a 500 error or a 400 one or something. – VLAZ Nov 02 '20 at 09:42
  • @VLAZ thank you both. I was returning html and trying to parse it as JSON – stressedkid Nov 02 '20 at 12:30

0 Answers0