1

I am trying to signup/login a user using JWT. For this I have a working API which I have created.

Now, I want to use that authentication API with my React/Redux App.

When a user signs up I dispatch an action from my Signup component -

const signUpHandler = (e) => {
    e.preventDefault();

    dispatch(signup(name, email, password));
  };

Now, in my userSlice I have the following reducer -

signup: (state, action) => {
      fetch("http://localhost:5000/user/signup", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(action.payload),
      })
        .then((res) => {
          return res.json();
        })
        .then((data) => {
          console.log(data);
        });
    },

After I click on Signup i.e; after the fetch process begins, I get this error -

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

After digging in a little bit, I found that this error occurs when the return type from fetch is not JSON. But my API works prefectly fine.

Any idea what might be the issue?

Thanks in advance.

vaibhav deep
  • 655
  • 1
  • 8
  • 27
  • 3
    Check what the response is. Since it starts with `<` it's very likely HTML and it's very likely that you get an error page that will direct you to what the problem is. – VLAZ Nov 03 '20 at 07:43
  • Does this answer your question? ["SyntaxError: Unexpected token < in JSON at position 0"](https://stackoverflow.com/questions/37280274/syntaxerror-unexpected-token-in-json-at-position-0) – VLAZ Nov 03 '20 at 07:43
  • In the Networks tab, the response is HTML which is a boilerplate with the same error above in a

    tag

    – vaibhav deep Nov 03 '20 at 07:46
  • I know that the response is HTML but what can I do to rectify it? – vaibhav deep Nov 03 '20 at 07:49
  • You can update the `signup` POST response to be in JSON format instead of HTML. Also check the network event response code. – Derek Nov 03 '20 at 07:54
  • You mean in `headers` should I add `Accept: "application/json",` ? The response code is 400. – vaibhav deep Nov 03 '20 at 07:59
  • You don't need to stringify the body, and I think you meant `Content-type` instead of `Content-Type`? –  Nov 03 '20 at 08:31
  • Shouldn't we sent data to the server in JSON format using stringify ? `action.payload` is just a JS object – vaibhav deep Nov 03 '20 at 09:09

1 Answers1

0

I just discovered the mistake and it was quite silly. This might prevent someone from committing the same mistake.

When dispatching the signup/login action,

instead of dispatch(signup(name, email, password));

Do - dispatch(signup({name, email, password}));

The main error was the action.payload was not what was expected(i.e; an object). As a result of which the data sent to the server was incorrect.

vaibhav deep
  • 655
  • 1
  • 8
  • 27