[英]How to switch on CORS for IBM Code Engine Application
I have created a Code Engine application which is exposing a couple of APIs.我创建了一个代码引擎应用程序,它公开了几个 API。 Its container is built using a Cloud Native Buildpack, so I can pick up fixes to security issues.它的容器是使用 Cloud Native Buildpack 构建的,因此我可以修复安全问题。
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 -我可以从浏览器和 curl 成功调用 API,但是当我尝试从 React.js 应用程序调用 API 时,出现以下错误 -
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.我需要在我的代码引擎应用程序上启用 cors,但正在努力确定如何。
The react.js app skeleton was created by running npx create-react-app
. react.js 应用程序框架是通过运行 npx npx create-react-app
。 I am testing the react.js app locally running npm start
.我正在测试本地运行npm start
的 react.js 应用程序。 When it is ready it will be built by running npm run build
.当它准备好时,它将通过运行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:对代码引擎应用程序 API 的 REST 调用是一次性使用useEffect
,其中endpoint
和method
是组件的输入:
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.对于 POST CORS 请求,您的应用必须提供 OPTIONS 预检请求。 Maybe that's the issue?也许这就是问题? See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS or other resources on CORS.请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS或 CORS 上的其他资源。 For POST requests in particular, you need to provide Access-Control-Allow-Headers options.特别是对于 POST 请求,您需要提供 Access-Control-Allow-Headers 选项。
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因为带有 API 的 Code Engine 应用程序是由 Node.js / Express 提供支持的,需要做的就是添加cors
作为依赖项,然后添加
const cors = require('cors');
app.use(cors());
See https://expressjs.com/en/resources/middleware/cors.html见https://expressjs.com/en/resources/middleware/cors.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.