我有一个React应用程序,试图从aws访问无服务器资源。但是我遇到了以下错误
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.test.com' is therefore not allowed access. The response had HTTP status code 502.
终端节点网址为https://key.execute-api.ap-southeast-2.amazonaws.com/dev/samplefunction
在 serverless.yml 中的设置为
login:
handler: login.login
events:
- http:
path: login
method: post
cors:
origin: 'https://admin.differentdomain.com'
headers:
- MY_CUSTOM_HEADER
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
还有其他地方需要进行CORS配置吗?
callback
的响应对象需要提供此标头。因此,您需要使用{statusCode: 200, headers: {Access-Control-Allow-Origin: "*"}, body: {} }
而不是{statusCode: 200, body: {} }
。假设您正在使用 Lambda 代理集成。 - Mike Patrickcors:
下添加allowCredentials: true
而不是只写cors: true
。在你的代码中添加头部也是必要的,所以请保留它。但这并不会被预检CORS请求调用,所以你还需要添加这个。 - V Maharajhx-api-key
值进行测试。这也导致了No 'Access-Control-Allow-Origin' header is present on the requested resource.
我花了一个小时找出它与无效的 'x-api-key' 标头值有关。发送正确的密钥后,它就可以工作了。Lambda 函数中我需要返回的唯一标头是"Access-Control-Allow-Origin": "*"
。 - A.W.