获得 502 响应和 'has been blocked by CORS policy' 运行 对我的 lambda 函数的简单提取请求

Getting 502 response and 'has been blocked by CORS policy' running a simple fetch request to my lambda function

使用无服务器框架在 AWS 上构建无服务器 Web 应用程序时,我收到一个 CORS 错误,其中包含针对 AWS Cognito 用户池进行身份验证的 502 响应代码

GET https://URL.amazonaws.com/dev/asset/ID-1178 502
index.html:1 Access to fetch at 'https://URL.amazonaws.com/dev/asset/PO-TIENDA1178' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
index.js:109 Uncaught (in promise) TypeError: Failed to fetch

几乎相同的请求适用于另一个功能。

这是从前端发送的两个 ajax 请求:


// working just fine

        async function getAllAssets() {
            const getAssetsUrl = _config.api.invokeUrl + "/assets"
            const response = await fetch(getAssetsUrl, {
                headers: { 
                    Authorization: authToken
                },
                type: "GET",
                dataType: 'json',
                crossDomain: true
            })
        }

// not working, throwing the error described above

        async function getOneAsset() {
            const getAssetsUrl = _config.api.invokeUrl + "/asset/" + "ID-1178"
            const response = await fetch(getAssetsUrl, {
                headers: { 
                    Authorization: authToken
                },
                type: "GET",
                dataType: 'json',
                crossDomain: true
            })
        }

我 运行 在同一个 window.

中两个函数 onDocReady

以下是 serverless.yaml 中的定义:

  # WORKS 
  getAssets:
    name: ${self:service}-${self:provider.stage}-get-assets
    handler: handler.getAssets
    role: InventoryLambdaRole
    events:
      - http:
          path: /assets
          method: get
          cors: true
          authorizer:
            arn: arn:aws:cognito-idp:eu-west-1:HARDCODED:ARN

  # doesn't work

  getAsset:
    name: ${self:service}-${self:provider.stage}-get-asset
    handler: handler.getAsset
    role: InventoryLambdaRole
    events:
      - http:
          path: /asset/{assetId}
          method: get
          cors: true
          authorizer:
            arn: arn:aws:cognito-idp:eu-west-1:HARDCODED:ARN

下面是我在 handler.js:

中的函数实现

// get all assets works fine:

module.exports.getAssets = function(event, context, callback) {
  const params = {
    TableName : 'Assets',
    Select: 'ALL_ATTRIBUTES',
  }

  const request = documentClient.scan(params, function(err, data) {
    if (err) {
      console.log("Error", err)
    } else {
      const itemCount = data.Count
      const response = {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Credentials': true,
        },
        body: JSON.stringify({
          itemCount: itemCount,
          assets: data
        }),
      }
      callback(null, response);
    }
  })
}

// get one asset doesn't work:
module.exports.getAsset = function(event, context, callback) {
  const params = {
    TableName : 'Assets',
    Key: {
      AssetId: event.pathParameters.assetId // also tried to just hardcode it like this: 'ID-1178' 
    }
  }

  const request = documentClient.get(params, function(err, data) {
    if (err) {
      console.log("Error", err)
    } else {
      const response = {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Credentials': true,
        },
        body: JSON.stringify({
          asset: data
        }),
      }
      callback(null, response);
    }
  })

虽然这是一个 CORS 错误,但正如您所见,提供了来源 headers,我发现结合 502 状态,它可能是 CORS 之前的错误,例如功能或授权方面的问题。但是,到目前为止,我看不出它们有任何问题。

无服务器函数本身在本地调用时也能正常工作: npm run sls -- invoke local --function getAsset -p test.json

您知道问题出在哪里或如何调试吗?

您的问题可能很简单 dynamodb:GetItem。这与列出所有(即查询或扫描)的权限不同