-1

I'm attempting to redirect the browser from the backend, but getting this cors error every time. In the backend, I used the CORS package, however, it appears that it did not work.

Here is client site of the code

useEffect(() => {
  async function getData() {
    try {
      // The params get from the url.
      const {
        data
      } = await axios.get(`http://localhost:5000/${url}`);
      setDestination(data);
    } catch (error) {
      setError(error.message);
    }
  }
  getData();
}, [url]);

useEffect(() => {
  if (destination) {
    window.location.replace(destination);
  }
}, [destination]);

Here is server site of the code

// app.js
const express = require("express");
const cors = require("cors");
const app = express();
app.use(express.urlencoded({
  extended: false
}));
app.use(express.json());
app.use(cors());

//redirect controller
exports.redirect = asyncErrorHandler(async(req, res, next) => {
  const shortUrl = await urlSchema.findOne({
    shortUrl: req.params.shortUrl
  });
  if (!shortUrl) {
    return next(new ErrorHandler("Invalid URL", 404));
  }
  const url = shortUrl.fullUrl;
  res.redirect(url);
});
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Sazzad Hossain
  • 131
  • 2
  • 11

1 Answers1

3

The server side code you've shown us, while CORS enabled, redirects to another URL.

When redirecting both the redirect response and the response to the subsequent request must grant permission with CORS.

You can't trick the browser into giving your JavasScript access to http://third-party.example.com/ (which isn't CORS enabled) by making a request to http://mine.example.net/ (which is) and redirecting to http://third-party.example.com/.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • As a result, I won't be able to redirect from the backend. Instead, I should send a json response, correct? Then use window.location.replace(destination) to redirect the browser. – Sazzad Hossain Mar 14 '22 at 18:16
  • Your client-side code expects a JSON response. It doesn't matter if that JSON comes from the URL originally requested or one you redirect to. It *does* matter that every URL that gets requested (directly or as a result of a redirect) grants permission via CORS. – Quentin Mar 14 '22 at 18:18