Javascript 为什么此AWS Amplify API被CORS策略阻止

Javascript 为什么此AWS Amplify API被CORS策略阻止,javascript,aws-lambda,cors,aws-api-gateway,aws-amplify,Javascript,Aws Lambda,Cors,Aws Api Gateway,Aws Amplify,AWS Amplify中的REST API是使用以下命令创建的。在不更改生成的Express函数中的任何代码的情况下,以下post请求将导致以下错误: Access to XMLHttpRequest at 'https://example-id.execute-api.ca-central-1.amazonaws.com/dev/example-path' from origin 'http://localhost:3000' has been blocked by CORS policy:

AWS Amplify中的REST API是使用以下命令创建的。在不更改生成的Express函数中的任何代码的情况下,以下post请求将导致以下错误:

Access to XMLHttpRequest at 'https://example-id.execute-api.ca-central-1.amazonaws.com/dev/example-path' from origin 'http://localhost:3000' 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. 放大命令

amplify add api ? Please select from one of the below mentioned services: REST ? Provide a friendly name for your resource to be used as a label for this category in the project: example ? Provide a path (e.g., /book/{isbn}): /example-path ? Choose a Lambda source Create a new Lambda function ? Provide a friendly name for your resource to be used as a label for this category in the project: example ? Provide the AWS Lambda function name: example ? Choose the runtime that you want to use: NodeJS ? Choose the function template that you want to use: Serverless ExpressJS function (Integration with API Gateway) ? Do you want to access other resources in this project from your Lambda function? No ? Do you want to invoke this function on a recurring schedule? No ? Do you want to configure Lambda layers for this function? No ? Do you want to edit the local lambda function now? No ? Restrict API access Yes ? Who should have access? Authenticated users only ? What kind of access do you want for Authenticated users? create, update, delete ? Do you want to add another path? No amplify push
const apiName = 'example';
const path = '/example-path';
const myInit = {
    body: JSON.stringify({
        example: example,
    })
};

API
.post(apiName, path, myInit)
.then(response => {
    console.log(response);
})
.catch(error => {
    console.log(error.response);
});

很可能你对CORS没有意见。我刚刚遇到了这个问题,通过cli生成了API。它抱怨CORS,和你的错误完全一样。一旦我将每个环境变量引用(即process.env.NODE_env)替换为它们的硬编码值并推送我的api,它就按预期工作了

邮递员对同一端点的请求是否有效?邮递员将忽略CORS,并应让您确定错误是否真的是CORS。如果这确实是一个CORS问题,那么在AWS控制台中检查该端点是否存在选项方法。您曾经解决过这个问题吗?我遇到了完全相同的问题。我可以调用未经身份验证的端点,但经过身份验证的端点会导致问题。
const apiName = 'example';
const path = '/example-path';
const myInit = {
    body: JSON.stringify({
        example: example,
    })
};

API
.post(apiName, path, myInit)
.then(response => {
    console.log(response);
})
.catch(error => {
    console.log(error.response);
});