Khpalwalk
Khpalwalk

Reputation: 981

Fetch POST Unexpected end of input Erorr

I'm trying to do a POST request for authentication in Redux and I'm passing email & password as the body but it returns this error in the console:

Uncaught (in promise) SyntaxError: Unexpected end of input

I looked around for the answer and many people suggested that it might be a missing } brace but I looked for it and I don't think it's that.

Here is my fetch function.

export function loginUser(creds) {

  let config = {
    mode: 'no-cors',
    method: 'POST',
    headers: { 'Content-Type':'application/x-www-form-urlencoded' },
    body: `email=${creds.email}&password=${creds.password}`
  };


  return dispatch => {
    dispatch(requestLogin(creds));
    return fetch('http://localhost:4000/api/authenticate', config)
    .then(response =>
      response.json()
      .then(user => ({ user, response }))
    ).then(({ user, response }) =>  {
      if (!response.ok) {
        dispatch(loginError(user.message));
        return Promise.reject(user);
      } else {
        localStorage.setItem('id_token', user.token);
        dispatch(receiveLogin(user));
      }
    });
  };
}

The fetch POST method calls the API and I see it in the networking tab and I see the response too but the fetch request stops at .then(response => after the url and config.

It's been two days and still can't find the solution. By the way, this works fine in Postman(chrome extension), so nothing wrong with the API.

Thanks

Answer EDIT: The issue was related to CORS, so for anyone having the same issue as I did.

Upvotes: 3

Views: 2143

Answers (2)

Integ
Integ

Reputation: 3953

I solve the same question when I remove

mode: 'no-cors'

from the config.

Upvotes: 1

JAYBEkster
JAYBEkster

Reputation: 790

Anyway you could simplify your snippet code to:

fetch('http://localhost:4000/api/authenticate', config)
  .then(response => response.json())
  .then(({ user, response }) =>  {

And you should might add catch method to handle an Error object.

Upvotes: 0

Related Questions