【问题标题】:CORS error when deployed, but works locally - Cogntio/SAM部署时出现 CORS 错误,但在本地工作 - Cogntio/SAM
【发布时间】:2021-06-18 10:14:56
【问题描述】:

我无法弄清楚为什么我在sam deploy 之后无法登录我的应用程序。我不断收到 CORS 丢失 Allow Origin

如果我使用 sam local start-api 在本地运行它,那么我会得到状态 200,因此它似乎可以在本地运行。我将 lambda 函数的 CORS 设置为 *,所以我不确定我需要更新什么。我有一个注册函数,它具有相同的响应头设置

            headers: {
                "Access-Control-Allow-Origin": "*", 
                "Access-Control-Allow-Credentials":
            },

但是 register 函数没有 CORS 问题,所以我认为 template.yaml 很好。我不确定还需要做什么。感谢您对此提供的任何帮助!

login.js

'use strict';
//global.fetch = require('node-fetch')
require('dotenv').config();
const Cognito = require('./confirm/cognito/index');
const { verify } = require('./confirm/cognito/index');


exports.handler = async (event) => {
    const json = JSON.parse(event.body)
    // console.log("EVENT BODY", event.body)

    const verificationResponse = await Cognito.signIn(json.email, json.password);
    console.log(verificationResponse)

    if (verificationResponse.statusCode !== 200) {

        console.log("Verification Error:", verificationResponse.response.message);
        const response = {
            statusCode: 500,
            body: JSON.stringify('failed to verify user'),
            headers: {
                "Access-Control-Allow-Origin": "*", 
                "Access-Control-Allow-Credentials": true
            },
        };
        return response;
    }


    const response = {
        statusCode: 200,
        body: JSON.stringify(statusCode),
        headers: {
            "Access-Control-Allow-Origin": "*", // Required for CORS support to work
            "Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS 
        },
    };
    return response;
};

Cognito.signIn 函数

function signIn(email, password) {
  return new Promise((resolve) => {
    AwsConfig.getCognitoUser(email).authenticateUser(AwsConfig.getAuthDetails(email, password), {
      onSuccess: (result) => {
        console.log("RESULT", result)
        const token = {
          accessToken: result.getAccessToken().getJwtToken(),
          idToken: result.getIdToken().getJwtToken(),
          refreshToken: result.getRefreshToken().getToken(),
        }
        return resolve({ statusCode: 200, response: AwsConfig.decodeJWTToken(token) });
      },

      onFailure: (err) => {
        console.log("ERROR HERE", err)
        return resolve({ statusCode: 400, response: err.message || JSON.stringify(err) });
      },
    });
  });
}

模板.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: REST API using SAM

Globals:
  Function:
    Runtime: nodejs12.x
    Environment:
      Variables:
        TABLE_NAME: !Ref Table
    MemorySize: 128
    Timeout: 5
  Api:
    Cors:
      AllowMethods: "'GET,POST,PUT,DELETE,OPTIONS'"
      AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'"
      AllowOrigin: "'*'"
      AllowCredentials: "'*'"

Resources:
  Table:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: userid
        Type: String
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1

   RegisterUser:
    Type: AWS::Serverless::Function
    Properties:
      Handler: register.handler
      Events:
        Register:
          Type: Api
          Properties:
            Path: /register
            Method: post

  LoginUser:
    Type: AWS::Serverless::Function
    Properties:
      Handler: login.handler
      Events:
        Login:
          Type: Api
          Properties:
            Path: /login
            Method: post
          

【问题讨论】:

  • 如果您将所有服务器放在一个公共域后面,您将不会遇到 CORS 问题,并且您不需要像您正在使用的那样使用不安全的标头配置。
  • 我可能会将 origin 标头更新为仅用于以后要使用的域,但我希望在开发过程中暂时在本地运行前端应用程序时让它工作。您能否就如何避免出现此错误提供任何建议?我让它在本地工作以进行注册,所以我只是不明白为什么登录会出现问题。
  • 使用反向代理将所有服务器放在同一个源/域后面,您根本不需要标头。

标签: node.js aws-lambda cors amazon-cognito aws-sam


【解决方案1】:

标题:{ “访问控制允许来源”:“*”, “访问控制允许凭据”:真 }

登录时缺少 HTTP 调用。在需要的地方提供标题

【讨论】:

    【解决方案2】:

    您可以使用 cors npm 模块: 这是链接:https://www.npmjs.com/package/cors

    var express = require('express')
    var cors = require('cors')
    var app = express()
    
    app.use(cors())
    
    app.get('/products/:id', function (req, res, next) {
      res.json({msg: 'This is CORS-enabled for all origins!'})
    })
    
    app.listen(80, function () {
     console.log('CORS-enabled web server listening on port 80')
    })
    

    【讨论】:

    • 我没有在我的解决方案中使用 express,所以我不太确定 cors 模块是否适用。
    猜你喜欢
    • 2023-01-11
    • 2021-02-16
    • 2020-03-11
    • 2017-01-25
    • 1970-01-01
    • 2018-10-22
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多