1) I have had my react app hosted in a S3 bucket served by Cloudfront with a custom domain.
2) Then I have my Express API server live on a Lightsail instance with Nginx/PM2.
Now I'm having 422 CORS issue when calling an endpoint from my React. I have tried the following:
1) Add the following CORS rules to the S3 bucket that contains my React app assets:
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>HEAD</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> 2) Pasted the Nginx config from here https://enable-cors.org/server_nginx.html to my api's server block:
server { location / { proxy_pass http://localhost:3000 ... ... if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # # Custom headers and headers various browsers *should* be OK with but aren't # ... ... 3) In my React app's cloudfront distribution's 'Behaviours' page:
- 'Cache Based on Selected Request Headers' -> Whitelist the
Originheader - Allowed all http methods...
- Forward all cookies...
- Forward all 'Query String Forwarding and Caching' too...
But still no luck.
I can get some response from running this: curl -s -D - -H "Origin: https://app.react.app" https://api.react.app/isOnline
curl -i -X OPTIONS https://api.react.app/isOnline gives me HTTP/1.1 204 No Content success.
What else can I try...? Appreciate any pointers..
add_header 'Access-Control-Allow-Origin' '*' always;— that is, append thealwayskeyword to youradd_headerdirectives. nginx.org/en/docs/http/ngx_http_headers_module.html#add_header. Otherwise, if you don’t do that, nginx will only add the Access-Control-Allow-Origin header to 2xx success responses and 3xx redirects — but not to 4xx errors. That will fix the CORS issue — but the problem will still be that the server’s responding with a 422 error rather than a 200 OK success response.curl -X OPTIONS [other args] [URL for your Express API endpoint]. Ifhttps://app.react.appis the URL for the React app that’s running the frontend code you’re making the request from, then when you test with curl, you don’t want to make the request tohttps://app.react.app— instead you want to make the request to your Express API endpoint.curl -i -X [URL for your Express API endpoint]gives meHTTP/1.1 204 No Contentas expected! But why still422and CORS in browser complaining can't read remote resource in myhttps://api.react.app/some_endpoint:(alwayswas the ticket. The422had nothing to do with CORS issue here(it's a error code I explicitly set, sorry!). If you would edit the question and create an answer for this, I would totally accept it! (Edit: I'm gonna try revert Item 1 and 3 and see if it still works..)