使用无服务器组件部署 Express 应用程序时如何停止'CORS missing allow origin error'?



当我的React前端调用我的Typescript Express REST API(使用无服务器组件托管在API网关上)时,我得到以下错误:

Access to XMLHttpRequest at 'https://randomId.execute-api.ap-southeast-2.amazonaws.com/userLoginSignup' from origin 'https://www.tueshey.com' 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.

我的app.ts的CORS配置是这样的(作为参考,这是我的整个文件):

...
const app = express();
// CORS
const allowlist = ['https://www.tueshey.com'];
const options: cors.CorsOptions = {
origin: allowlist,
};
app.use(cors(options));
...

当我在本地检查请求时,有一个OPTIONS请求首先返回,其中包括允许访问起源头,但不是当我部署它时。本地运行正常

您还必须在API网关上启用CORS。当单击API Gateway上的资源端点时,在操作上有Enable CORS。这也会为你的资源添加Options方法。如果你想要一些定制,你必须手动添加OPTIONS方法

最新更新