0

Try to parse the response body text as JSON (response.json()) and got this error in the console:

Uncaught (in promise) SyntaxError: Unexpected end of input (at script.js:177:33)at postData (script.js:177:33)

This is the code that throw the error in the line of .then(response => response.json()).

fetch('/', {
    method: 'POST', // or 'PUT'
    mode: 'no-cors',
    headers: {
      'Content-Type': 'application/json',
    },
    redirect: 'follow',
    referrerPolicy: 'origin-when-cross-origin',
    body: JSON.stringify({
      "email": emails.val()
    }),
  })
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

I expect it to post data (emails.val()) to the body of the endpoint so I can use the controller I wrote to take the data from this endpoint and insert it to model.

Anuga
  • 2,619
  • 1
  • 18
  • 27
  • 3
    The response to the request is not valid JSON. Check the request in devtools to see what the responseText is, and debug it in your server side. – Rory McCrossan Jan 23 '23 at 14:43
  • is your response actually returning proper json? – Daniel A. White Jan 23 '23 at 14:43
  • `mode: no-cors` is probably not what you want. See: https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors – Reyno Jan 23 '23 at 14:45
  • I tried to check the response before parsing it with "if (!response.ok) { throw Error(response.statusText); } " it throwing error – lomax osomba Jan 23 '23 at 14:51
  • Add the code where you "create" `emails`, where it gets `.val()` from. You input data isn't valid JSON. it never does the request so it never gets a response. – Anuga Jan 23 '23 at 14:55
  • I think the error message is indicating that the json encountered the end of the input before it was able to fully parse the data but I'm not 100% sure how if it's related to async or defer problem in JS – lomax osomba Jan 23 '23 at 14:56
  • This is the HTML: **** And this is the Js: where the val is from **const emails = $('.email');** – lomax osomba Jan 23 '23 at 14:58
  • replace response.json() by response.text() just to see what you get? – Salketer Jan 23 '23 at 15:38
  • replaced by response.text() and passed, Thanks! do you have an idea why it can't pass with json? – lomax osomba Jan 23 '23 at 16:00

0 Answers0