如何在使用Serverless Component部署Express应用时停止’CORS缺少允许来源错误’?

huangapple go评论70阅读模式
英文:

How to stop 'CORS missing allow origin error' when deploying Express application using Serverless Component?

问题

当我的React前端调用我的TypeScript Express REST API(托管在API Gateway上,使用Serverless Components)时,我遇到以下错误:

来自源 'https://www.tueshey.com' 的 XMLHttpRequest 访问被 CORS 策略阻止:响应预检请求未通过访问控制检查:所请求的资源上没有 'Access-Control-Allow-Origin' 标头。

我的app.ts中的CORS配置如下(供参考,这里是我的整个文件):

...
const app = express();

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

当我在本地检查请求时,首先会返回一个包含Allow Access Origin标头的OPTIONS请求,但部署时则不会。在本地正常工作。

英文:

When my React frontend calls my Typescript Express REST API (hosted on API Gateway using Serverless Components), I get the following error:

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.

My app.ts CORS config is like this (for reference, here's my whole file):

...
const app = express();

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

When I inspect the request locally, there is an OPTIONS request that returns first that includes the Allow Access Origin header but not when I deploy it. It is working correctly locally.

答案1

得分: 2

你还需要在API网关上启用CORS。在API网关上点击资源端点时,在操作中会有“启用CORS”选项。这将为您的资源添加Options方法。如果您想进行一些定制,您将需要手动添加OPTIONS方法。

英文:

you will have to enable CORS on API Gateway as well. When click on the resource endpoint on API Gateway, on actions there is Enable CORS. That will add Options method also for your resource. If you want some customization you will have to add OPTIONS method manually

huangapple
  • 本文由 发表于 2023年1月9日 15:14:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定