Reputation: 490
I am working on a small school project that involves accessing a microservice built with Micronaut in java from a react frontend. When I initially deployed my microservice to Google cloud I was able to access it remotely from Postman, however, when I tried to access it from the react front-end I got the following error:
Code:
sendOtp(phoneNumber) {
fetch(apiRequest, {
method: 'POST',
body: JSON.stringify({
phoneNumber: 'phoneNumber',
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
}).then(response => {
return response.json()
}).then(json => {
this.setState({
otpResponse:json
});
});
}
Error:
Access to fetch at 'X' from origin 'X' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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
I looked into CORS a bit and found that I needed to add the following to my application.yml
file:
micronaut:
server:
cors:
enabled: true
I also added https://cors-anywhere.herokuapp.com
to my post request as it was a workaround that I found online.
However, I still have a few questions regarding this:
1. Why I am able to access this microservice from Postman but not from the React frontend?
2. Is using https://cors-anywhere.herokuapp.com
a safe workaround? Are they any security issues?
3. Is this issue exclusive to a React/Web pages? Would I need to enable CORS if I wanted to access this microservice from other applications?
Thanks, any help would be appreciated!
Upvotes: 4
Views: 9005
Reputation: 27200
- Why I am able to access this microservice from Postman but not from the React frontend?
Because CORS isn't relevant to your Postman requests.
- Is using https://cors-anywhere.herokuapp.com a safe workaround? Are they any security issues?
In generally you don't want to do that. You want configure the CORS to allow requests from your front end.
- Is this issue exclusive to a React/Web pages? Would I need to enable CORS if I wanted to access this microservice from other applications?
No, it isn't exclusive to React. Whether or not you need to enable CORS to access this service from other applications depends on what those applications are. If they are JS apps running in browsers served up from different origins, yes. If they are client applications making requests to your API, no.
Look at the Allowed Origins section at https://docs.micronaut.io/1.2.5/guide/index.html#cors. You will need to configure whatever origin your React app is served from.
I hope that helps.
Upvotes: 4