1

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?

Chris
  • 18,724
  • 6
  • 46
  • 80
sssaini
  • 375
  • 1
  • 2
  • 14
  • 4
    You would do the redirect in the fetch's `then()` callback, ie `window.location="someurl"`. Having the redirect on the server side is making it so the fetch request goes to the url and does not change the page the user is currently on. – Patrick Evans Oct 19 '20 at 00:26
  • Please have a look at [this answer](https://stackoverflow.com/a/75188418/17865804) – Chris Apr 07 '23 at 17:03

2 Answers2

2

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

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);
});