Configuring CORS for SAM. API works with postman, but not angular

user6680

I'm having issues registering a user in my angular app using the same endpoint that postman uses. Postman works fine and the user appears in the cognito user pool no problem, but if I try and register the user via my registration page in my angular app, then I get a CORS error enter image description here

When I look at API gateway, I noticed there isn't an options section in the different endpoints so maybe this an issue.

enter image description here

Also when I deploy SAM I get that there is not authorization set so this could be a factor too. Not sure though. How can I configure my SAM template to make CORS work with the app and not just for postman? I appreciate any help!

SAM Template

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

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

  ConfirmUser:
    Type: AWS::Serverless::Function
    Properties:
      Handler: confirm.handler
      Events:
        GetUser:
          Type: Api
          Properties:
            Path: /confirm
            Method: post

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

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

register.js

const AWS = require('aws-sdk');
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
global.fetch = require('node-fetch');

const UserPoolId = "<my user poolId>"
const ClientId = "<my client id>"

const poolData = {
    UserPoolId,
    ClientId
}

AWS.config.update({
    region: 'us-east-1'
})

async function registerUser(json) {
    const {
        email,
        password
    } = json

    return new Promise((resolve, reject) => {
        let attributeList = []

        attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({ Name: "email", Value: email }));


        const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

        userPool.signUp(email, password, attributeList, null, function (err, result) {
            if (err) {
                return resolve({
                    statusCode: 500,
                    err
                })
            }

            resolve({
                statusCode: 200,
                message: 'User successfully registered'
            })
        })
    })
}

exports.handler = async function (event, context, callback) {
    console.log("EVENT BODY", event.body)
    const json = JSON.parse(event.body)
    let result;
    let response;
    try {
        result = await registerUser(json);

        response = {
            statusCode: 200,
            body: JSON.stringify('User registered successfully'),
            headers: {
                "Access-Control-Allow-Origin": "*", // Required for CORS support to work
                "Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS 
            },
        };
    } catch (e) {
        response = {
            statusCode: 500,
            body: JSON.stringify('Failed to register user'),
            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;

}
Balu Vyamajala

we need to have an OPTIONS method returning below three headers for Browser to allow CORS

Access-Control-Allow-Headers should contain all headers
Access-Control-Allow-Methods should contain all methods
Access-Control-Allow-Origin should contain the host or '*'

Adding below template to SAM Globals will add necessary OPTIONS method for every method pointing to Mock Integration.

All the additional Headers if any should be added in AllowHeaders

Globals:
  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: "'*'"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Configuring CORS for SAM. API works with postman, but not angular

From Dev

Node.js API - Works with Postman but not works in Angular.js

From Dev

API call works on postman but not on filemaker

From Dev

Angular CORS works for GET but not for DELETE

From Dev

Calling Twitter API from Postman works, but from Angular 2 app it doesnt'

From Java

CORS with POSTMAN

From Dev

Web API CORS Angular $resource

From Dev

Configuring CORS for nginx and passenger

From Dev

Can't add user to couchDB via angular but works with postman

From Dev

400 Error on API endpoint in Guzzle that works fine in Browser & Postman

From Dev

React Native + fetch + API : DELETE request fails in App, works in Postman

From Dev

Error accessing a Web API which works well using POSTMAN

From Dev

CORS works for access token but not for refresh token in Web Api 2

From Dev

Web API 2 - CORS only works over HTTPS (not HTTP)

From Dev

Cors for GET with Postman not showing headers

From Dev

Globally configuring Angular directives

From Dev

Angular 4 - configuring systemjs

From Dev

Angular and CORS

From Dev

Angular and CORS

From Dev

Configuring CORS for a Team Foundation Server extension

From Dev

Cors Not working even when configuring in webapi config

From Dev

Power BI embed API access token request works through Postman but not through code

From Dev

Java Spring error 404 while trying to get JSON from API. Works in postman

From Dev

Power BI embed API access token request works through Postman but not through code

From Dev

Call symfony 2 rest api with Angular JS, cors

From Dev

Getting CORS error from appveyor rest api using angular

From Dev

Getting CORS error from appveyor rest api using angular

From Dev

How to do a server side API call in angular to bypass CORS error

From Dev

Rest API with LocomotiveJs using CORS. Works on local machine but not on Amazon or Heroku

Related Related

  1. 1

    Configuring CORS for SAM. API works with postman, but not angular

  2. 2

    Node.js API - Works with Postman but not works in Angular.js

  3. 3

    API call works on postman but not on filemaker

  4. 4

    Angular CORS works for GET but not for DELETE

  5. 5

    Calling Twitter API from Postman works, but from Angular 2 app it doesnt'

  6. 6

    CORS with POSTMAN

  7. 7

    Web API CORS Angular $resource

  8. 8

    Configuring CORS for nginx and passenger

  9. 9

    Can't add user to couchDB via angular but works with postman

  10. 10

    400 Error on API endpoint in Guzzle that works fine in Browser & Postman

  11. 11

    React Native + fetch + API : DELETE request fails in App, works in Postman

  12. 12

    Error accessing a Web API which works well using POSTMAN

  13. 13

    CORS works for access token but not for refresh token in Web Api 2

  14. 14

    Web API 2 - CORS only works over HTTPS (not HTTP)

  15. 15

    Cors for GET with Postman not showing headers

  16. 16

    Globally configuring Angular directives

  17. 17

    Angular 4 - configuring systemjs

  18. 18

    Angular and CORS

  19. 19

    Angular and CORS

  20. 20

    Configuring CORS for a Team Foundation Server extension

  21. 21

    Cors Not working even when configuring in webapi config

  22. 22

    Power BI embed API access token request works through Postman but not through code

  23. 23

    Java Spring error 404 while trying to get JSON from API. Works in postman

  24. 24

    Power BI embed API access token request works through Postman but not through code

  25. 25

    Call symfony 2 rest api with Angular JS, cors

  26. 26

    Getting CORS error from appveyor rest api using angular

  27. 27

    Getting CORS error from appveyor rest api using angular

  28. 28

    How to do a server side API call in angular to bypass CORS error

  29. 29

    Rest API with LocomotiveJs using CORS. Works on local machine but not on Amazon or Heroku

HotTag

Archive