我有一个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配置吗?
答案 0 :(得分:0)
在Serverless中的CORS设置在这里详细说明:https://serverless.com/blog/cors-api-gateway-survival-guide/
除了serverless.yml中的配置(用于预检请求)之外,您还需要从代码中返回标头Access-Control-Allow-Origin
和Access-Control-Allow-Credentials
。在您的示例和Node.js实现中:
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': 'https://admin.differentdomain.com',
'Access-Control-Allow-Credentials': true,
},
body: {},
};
请确保在第一个标头中包含“ https”部分,我之前偶然发现了该内容。