1

I have been trying to make a login page in reactjs but it's throwing me an error in console like SyntaxError: Unexpected token r in JSON at position 0 but I got 200 status code in network tab and also I'm getting "redirect" in both response and preview tab under the network tab.

I tried the same code(except it was if(response.ok) this time) with another server of my friend and it successfully redirects it to another page

This is the code that I've been trying: is response.data not correct for reactjs?

  performLogin = async () => {
    var body = {
      password: this.state.password,
      email: this.state.email
    };
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify(body)
    };
    const url = "/api/authenticate";
    try {
      const response = await fetch(url, options);
      const result = await response.json();
      console.log(response);     //nothing is showing in console for this statement
      if (response.data == "redirect") {
        this.props.history.push(`/verifyOtp/${this.state.email}`);
      } else {
        console.log("login failed");
        window.alert("login failed");
      }
    } catch (error) {
      console.error(error);
    }
  };

edit: I also tried it in postman and it gives "redirect" as response in postman so the api must be working fine

UbuntuNewb
  • 411
  • 4
  • 13
  • instead of passing Accept, can you pass like "Accept" stringify and try ?, let me know if it worked for you!! – Learner Dec 16 '19 at 12:09
  • the quotes disappear themselves when I save the file – UbuntuNewb Dec 16 '19 at 12:13
  • "I also tried it in postman and it gives "redirect" as response in postman so the api must be working fine" — It gives "redirect" and the error message says that the problem is that the data isn't value JSON because it has an `r` as the first character … so that doesn't seem "fine" to me. – Quentin Dec 16 '19 at 12:20
  • What should I change in my code then @Quentin? – UbuntuNewb Dec 16 '19 at 12:35
  • Either change the server so it sends back JSON or change the client so it doesn't expect JSON. – Quentin Dec 16 '19 at 13:04
  • how do I change the client in front end? @Quentin it was an angularjs code that I tried to translate in reactjs but isn't working in reactjs but whereas it's working with angularjs with the same ```return $http.post('/api/authenticate',$scope.newuser).then(function(response,status){ if(response.data=='redirect'){ $window.location.href="/home"; ``` – UbuntuNewb Dec 16 '19 at 16:06
  • Replace `response.json();` with something suitable for the data format you are using!! – Quentin Dec 16 '19 at 16:07

1 Answers1

1

Your problem is in this line

const result = await response.json();

Your response is ok, everything is ok, but when you try to do response.json() and the response from the request isn't a valid json (maybe just a normal text), it will give you that error.

Because response can be a text or a json, you need to do some checking. Where is how to check if response is a json

This is kind of bad because on every request you will need to do this type of checking (transform it to text, try to parse, bla bla...), so What I recommend it you to use something better than fetch.

Axios is very good because it already do that checking.

For your example:

performLogin = async () => {

    var body = {
      password: this.state.password,
      email: this.state.email
    };
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify(body)
    };
    const url = "/api/authenticate";

    try {
      const response = await fetch(url, options); // Fetch the resource
      const text = await response.text(); // Parse it as text
      const data = JSON.parse(text); // Try to parse it as json
      // Do your JSON handling here
    } catch(err) {
      // This probably means your response is text, do you text handling here
    }
}
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • so I should remove this line? – UbuntuNewb Dec 16 '19 at 12:12
  • @UbuntuNewb no, you need a different aproach, I will edit my question – Vencovsky Dec 16 '19 at 12:15
  • I'm quite new, can you show how I should approach here? – UbuntuNewb Dec 16 '19 at 12:18
  • after the const data line, should I use this line ```if (data == "redirect") { this.props.history.push(`/verifyOtp/${this.state.email}`);```? – UbuntuNewb Dec 16 '19 at 12:25
  • @UbuntuNewb you can do what ever you want after that line – Vencovsky Dec 16 '19 at 12:27
  • I don't want to do much. I just want to confirm that ```if(response.data== redirect)``` then the page redirects me otp page. so now should it just be ```if(data=="redirect")```? – UbuntuNewb Dec 16 '19 at 12:31
  • @UbuntuNewb I'm not sure, because I don't know what is `response.data`. That is something you need to decide – Vencovsky Dec 16 '19 at 12:40
  • I just want to redirect to the other page. what I'm trying to explain is that when I try it in postman, I get "redirect" as a response there, just "redirect" and nothing else. now I want to match that same in my webapp that when I get response as 'redirect' then it should redirect me to the otp page. i have tried response.data=='redirect', didn't work, tried data=='redirect', didn't work either, getting the same syntaxerror as above in my question – UbuntuNewb Dec 16 '19 at 12:53