I have created a Code Engine application which is exposing a couple of APIs. Its container is built using a Cloud Native Buildpack, so I can pick up fixes to security issues.
I can successfully invoke the APIs from a browser and from curl, but when I attempt to invoke the APIs from a React.js app, I get the following error -
Access to fetch at '...' from origin 'http://localhost:3000'
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.
I need to enable cors on my code-engine application, but am struggling to determine how.
The react.js app skeleton was created by running npx create-react-app
. I am testing the react.js app locally running npm start
. When it is ready it will be built by running npm run build
.
The REST call to the Code Engine Application API is in a fire one time useEffect
, where endpoint
and method
are inputs to the component:
useEffect(() => {
if (!endpoint || !method) return;
console.log('Starting');
const appurl = `https://${endpoint}${method}`;
fetch(appurl, {
method: 'GET',
headers: {
"Content-Type": "application/json"
}
})
//.then(response => response.json())
.then(response => console.log(response))
.catch(console.error);
console.log('url is ', appurl);
},[]);
For POST CORS requests, your app has to serve the OPTIONS preflight request. Maybe that’s the issue? See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS or other resources on CORS. For POST requests in particular, you need to provide Access-Control-Allow-Headers options.
Because the Code Engine app with the API is powered by Node.js / Express, and all that needs to be done is to add cors
as a dependency, then add
const cors = require('cors');
app.use(cors());