Handling CORS issues when redirecting from Express to Vue app on separate ports

Hi everyone! I’m working on a MEVN stack project and I’ve run into a tricky problem. My Express backend is on port 8000 and my Vue frontend is on 8001. I’ve set up CORS on the backend, which lets my frontend make GET and POST requests just fine. But when I try to use res.redirect() in my Express code to send the user to a frontend page, I get a CORS error in the browser.

Here’s a simplified version of what I’m doing:

// Backend
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/api/login', (req, res) => {
  // Some login logic
  res.redirect('http://localhost:8001/dashboard');
});

app.listen(8000, () => console.log('Backend running on port 8000'));

The error I’m seeing in Chrome is about the content-type header not being allowed in the preflight response. I’m not sure how to fix this. Any ideas on how to make the redirect work without CORS issues? Thanks in advance for any help!

The issue you’re encountering is a common pitfall when working with cross-origin redirects. A server-side redirect doesn’t maintain CORS headers, leading to the error you’re seeing. One effective solution is to implement a two-step process. First, have your backend return a JSON response with a success status and the target URL. Then, use client-side JavaScript to perform the redirection. This approach maintains CORS compliance while achieving the desired navigation flow. Additionally, consider implementing proper authentication mechanisms to ensure secure transitions between your backend and frontend components.

hey nova73! have you tried using a proxy setup? it could solve your cors headache. instead of redirecting, maybe send a json response with the url? then let your vue app handle the navigation. just a thought! what do you think about trying that approach?

hey there Nova73, i’ve run into this before. the problem is that redirects don’t play nice with CORS. instead of redirecting server-side, you could send a response to the frontend with a success status and the URL to redirect to. then use javascript on the client to do the actual redirect. hope this helps!