0

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"); } }); }); 
1
  • For redirect you can check if the HTTP code is in the 300 range, which is provided in res.status. It won't take dot notation, So, you can use then(res => { if(res.status >= 300 && res.status < 400){ // redirect } else { return res.json(); } }) .then(data => { //handle your json data }); Commented Jun 28, 2020 at 9:31

1 Answer 1

1

For redirect you can check if the HTTP code is in the 300 range, which is provided in res.status. It won't take dot notation, So, you can use

.then(res => { if(res.status >= 300 && res.status < 400){ // redirect } else { return res.json(); } }) .then(data => { //handle your json data }); 

It would be a syntax error to use a dot in the callback argument like: .then((res.json) => {

However, it would be possible to deconstruct an object like this: .then(({ status, json }) => {

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.