Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'

In your then you should check if the response is OK before returning response.json:

.then(function (response) {
    if (!response.ok) {
        return Promise.reject('some reason');
    }

    return response.json();

})

If you want to have the error message in your rejected promise, you can do something like:

.then(function (response) {
    if (!response.ok) {
       return response.text().then(result => Promise.reject(new Error(result)));
    }

    return response.json();
})

You need to remove the mode: 'no-cors' setting from your request. Setting no-cors mode is exactly the cause of the problem you’re having.

A no-cors request makes the response type opaque. The log snippet in the question shows that. Opaque means your frontend JavaScript code can’t see the response body or headers.

https://developer.mozilla.org/en-US/docs/Web/API/Request/mode explains:

no-cors — JavaScript may not access any properties of the resulting Response

So the effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.”

People sometimes try setting no-cors mode when a response doesn’t include the Access-Control-Allow-Origin response header or else because the request is one that triggers a CORS preflight, and so your browser does an OPTIONS preflight.

But using no-cors mode isn’t a solution to those problems. The solution is either to:

  • configure the server to which you’re making the request such that it sends the Access-Control-Allow-Origin response header, and such that it handles OPTIONS requests

  • or set up a CORS proxy using code from https://github.com/Rob--W/cors-anywhere/ or such; see the How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API


I know this answer might be super late and might have been resolved but i just had the same issue today and I just needed to add a ',' at the end of the headers hash and i stopped getting the error

export function addContacts(formData) {
  return(dispatch) => {
    dispatch({type: 'POSTING_CONTACTS'});
    console.log(formData)
    return fetch(uri, {
      method: 'POST',
      body: JSON.stringify({contact: {name: formData.name, phone_number: formData.phoneNumber}}),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
    })
    .then(response => {
        return response.json()
      }).then(responseJSON => {
        console.log(responseJSON)
        return dispatch({type: 'ADD_CONTACT', payload: responseJSON});
      })
  }
}