Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect after fetch() call using nodejs express

I am trying to redirect to another URL after a POST FETCH call.

fetch("/", { method: "POST", redirect: "follow" })
        .then((res) => {
          console.log(res);
})
        .catch(function (err) {
          console.info(err + " url: ");
});

The backend is an Express endpoint with a simple redirect like so,

var cors = require('cors');
app.use(cors());

app.post("/", (req, res) => {
  res.redirect("https://google.com");
});

I want to change window.location after fetch call resolves the promise but the call fails with,

Access to fetch at 'https://google.com/' (redirected from 'http://localhost:3000/') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I understand that the error is because I am accessing google.com which has CORS enabled and I am not allowed to fetch data, but I just want to be able to redirect to that URL. Is there a different way I should be doing this?

like image 639
sssaini Avatar asked Nov 28 '25 11:11

sssaini


2 Answers

Ajax calls NEVER change the web page that the browser displays. They return a result to your Javascript. If the server sends back a 302 and you don't ask fetch() to follow the redirect, then you will get the 302 response and you can read the location header directly from that response. If you do ask fetch() to follow the redirect (and security allows), then it will follow the redirect and get you that new page's content back to your Javascript. Either way, the response comes to your Javascript and does not change what is displayed in the browser.

If you want an Ajax call to change the web page that is displayed in the browser, then you must set window.location to a new URL in your Javascript that receives the 302 redirect response from the Ajax call.

like image 143
jfriend00 Avatar answered Nov 30 '25 01:11

jfriend00


You should redirect from client side not from Server side!

Server side code

app.post("/", (req, res) => {
  res.send(200);
});

Client side code

fetch("/", { method: "POST" }).then((res) => {
    window.location.href = "https://google.com";
}).catch(function (err) {
    console.info(err);
});
like image 45
Tolui Davaasuren Avatar answered Nov 30 '25 01:11

Tolui Davaasuren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!