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!