i have a react app running on localhost:3000 and call api from spring cloud gateway running on localhost:8060
the gateway act as oauth2 client
the spring authorization server running on localhost:8000
when call an api from react it get cors error
whats my problem ?
The easiest solution is to serve both the REST API and the React app through the gateway: from the browser point of view, all requests would have the same origin (the gateway) which removes the need for any CORS configuration.
Gateway configuration will have at least two routes. Something like:
spring:
cloud:
gateway:
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
routes:
- id: api
uri: http://localhost:8000
predicates:
- Path=/api/**
filters:
- SaveSession
- TokenRelay=
- StripPrefix=1
- id: ui
uri: http://localhost:3000
predicates:
- Path=/ui/**
You then point your browser to http://localhost:8060/ui
. Of course, this also requires to configure the React app with /ui
as basePath
and to prefix requests to API with /api
.
You may also add /ui/**
to the list of permitAll
path matchers (you probably want users to load the React app before they are authenticated).
I have a written a complete tutorial for Baeldung there.