为什么这个 AWS Amplify API 被 CORS 策略阻止

cra*_*den 5 javascript cors aws-lambda aws-api-gateway aws-amplify

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

CORS 策略已阻止从源“http://localhost:3000”访问“https://example-id.execute-api.ca-central-1.amazonaws.com/dev/example-path”的 XMLHttpRequest :对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

默认情况下,Express 函数Enable CORS for all methods在第 行的注释下包含避免 CORS 问题的代码21。可以做些什么来允许将请求传递到 API 函数中?

app.js 中的默认 Express 代码(后端)

// Enable CORS for all methods
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
});

// Example POST method
app.post('/example-path', function(req, res) {
  // Add your code here
  res.json({success: 'post call succeed!', url: req.url, body: req.body})
});
Run Code Online (Sandbox Code Playgroud)

放大命令

放大添加api

? 请从以下提到的服务中选择一项:REST
? 为您的资源提供一个友好名称,以用作项目中此类别的标签:示例
? 提供路径(例如,/book/{isbn}):/example-path
? 选择一个 Lambda 源 创建一个新的 Lambda 函数
? 为您的资源提供一个友好名称,以用作项目中此类别的标签:示例
? 提供 AWS Lambda 函数名称:示例
? 选择要使用的运行时:NodeJS
? 选择您要使用的函数模板:Serverless ExpressJS 函数(与 API 网关集成)
? 您想从您的 Lambda 函数访问此项目中的其他资源吗?不
? 您想定期调用此函数吗?不
? 您要为此函数配置 Lambda 层吗?不
? 现在要编辑本地 lambda 函数吗?不

? 限制 API 访问 是
? 谁应该有权访问?仅限经过身份验证的用户
? 您希望经过身份验证的用户获得什么样的访问权限?创建、更新、删除
? 您要添加另一条路径吗?不

放大推

组件.js

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);
});
Run Code Online (Sandbox Code Playgroud)

小智 0

您可能对 CORS 没有任何疑问。我刚刚遇到这个问题,通过 cli 生成我的 API。它抱怨 CORS,与您的错误相同。当我用硬编码值替换每个环境变量引用(即 process.env.NODE_ENV)并推送我的 api 后,它就按预期工作了