在AWS Amplify和DynamoDB的Angular应用中,当使用GraphQL的POST操作时,可能会遇到CORS错误。解决方法是在用于托管应用程序的Bucket中设置CORS配置,以允许从特定或所有来源发出HTTP请求。此外,还应该在AWS Amplify中配置正确的API名称和区域,并使用正确的API密钥和安全凭据。以下是修改后的代码示例:
const apiName = 'myApiName';
const region = 'myRegion';
const config = {
API: {
endpoints: [
{
name: apiName,
endpoint: `https://my-api-id.execute-api.${region}.amazonaws.com/myApiStage`,
region: region,
custom_header: async () => {
return { Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}` };
}
}
]
}
};
Amplify.configure(config);
另外,请在Bucket的CORS配置中添加如下内容:
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"POST",
"PUT",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]