Thursday, 15 April 2021

react client wont follow redirect CORS localhost

front end: localhost:3000 (react app) App.js (client) on load call api '/'

function fetch_redirect() {
  fetch("http://localhost:8082")
}

function App() {
  return <div className="App">{fetch_redirect()}</div>;
}

export default App;

backend: localhost:8082 (nodejs express app) send redirect to /test endpoint on client

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

const whitelist = ['http://localhost:3000']
const corsOptions = {
  origin: function (origin, callback) {
      console.log(origin, whitelist.indexOf(origin) !== -1);
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.use(cors(corsOptions))
app.get('/', function (req, res) {
          res.redirect('http://localhost:3000/test')
    })
     
    app.listen(8082)

The main issue is on the client (react) once the api call is made, the redirect is blocked... how can I make the client react app follow this redirect to 'http://localhost:3000/test' I already have cors on my backend with enabled whitelist of localhost:3000 to allow me to make the api call not blocked... however the redirect is now blocked from the fetch frontend!

error details: Access to fetch at 'http://localhost:3000/test' (redirected from 'http://localhost:8082/') 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.



from react client wont follow redirect CORS localhost

No comments:

Post a Comment