Differentiate redirect/JSON-data in response from fetch request

Hi Guys,
i am trying to build a logic at front end to differentiate between the redirect and JSON response, the end goal for this is as, if the response is redirect go to that page and if the response is having data then it will render that data on the page.

  • Note: it is working fine if the back end send response as either res.redirect or res.json, but i am struggling (as in below code) as when i have to check first as what the response is from back end , i thought as if i can use if else statement at front end to disgusting between res.json and res.respond, i have tried like .then(res.redirect=>{…}).then(res.json=>{}) but it doesn’t look like if i am using the correct logic.

Any suggestions please, thanks :slightly_smiling_face:

Snippet from my front end code is .

const request = new Request("http://localhost:5000/api/newuser", options);

    (async () => {

      const incomingdata = await fetch(request)
// below i  differetiated the incoming response as if it is res.redirect or res.json data but didnt work
        .then((res.redirect) => {                  

          window.location.href = res.url;

        })
         .then((res.json) => {

            console.log("cannot find data");

          })

        .catch((err) => console.log("err"));

Snippet from my bank end code is,

connection.query("SELECT * FROM  users WHERE email=?;", [x1.Email], function (

    err,

    results

  ) {

    console.log("74",results, err);

    console.log("75",results[0].email);

    if (err) throw err;

    else {

      if (results[0].email && results[0].password) {

        console.log("79",results[0].email);

        //console.log(results[0]);

        if (results[0].password == x1.password)

          res.redirect("http://localhost:3000/");

        else {

          res.json({

            data: "invalid password",

          });

        }

      } else res.redirect("http://localhost:3000/about");

    }

  });

});

I found the solution, i need to use res.status=200… value in order to differentiate the link otherwise use res.json() if the data is returned from server.

1 Like