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 an 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.
vite
and everything works fine. You probably need to modify your5 client dev server – Mr. Hedgehoghttp://localhost:3000
. The reason is, when a request gets redirected across origins, the browser sets the Origin request header to null. So when the localhost:8082 express code sees the request, the Origin value isnull
, nothttp://localhost:3000
. – sideshowbarker