sst.dev icon indicating copy to clipboard operation
sst.dev copied to clipboard

Comments: Call the Create API

Open jayair opened this issue 9 years ago • 58 comments

Link to chapter - http://serverless-stack.com/chapters/call-the-create-api.html

jayair avatar Apr 10 '17 01:04 jayair

In the NewNote.js edit for handleSubmit, the path should be "/" instead of "/notes" since, when you create the back end the full path will be /prod/notes so by making the handleSubmit string "/notes" it'll try to make the REST call to /prod/notes/notes and fail.

Alternatively, you could be more specific in the config.js portion of this page to specify what you mean by YOUR_API_GATEWAY_URL

petecj2 avatar Apr 19 '17 21:04 petecj2

Just make

apiGateway: {
    URL: 'https://ngh4urud.execute-api.eu-west-1.amazonaws.com/prod',
  },

But I now have Cors issue where it seems its not enabled. Fetch API cannot load https://ngh4urud.execute-api.eu-west-1.amazonaws.com/prod/notes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 502. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

PatrykTies avatar Apr 29 '17 15:04 PatrykTies

@nerdguru added some context to it - 49da60e3aacf20bcede1b1f03433122783b312b2

@PatrykTies you can check your serverless.yml to see if you've enabled CORS there - https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/master/serverless.yml#L43

jayair avatar Apr 29 '17 20:04 jayair

After taking it so far, all I when I try to submit the note is an alert that says "failed to fetch". I also had a problem with the curl in this chapter: [http://serverless-stack.com/chapters/deploy-the-apis.html](Deploying the API) but I wasn't able to resolve it. The error there was "Internal Server Error"... Can you give me a pointer where I should start looking for more information on the problems?

frittate avatar May 24 '17 10:05 frittate

@frittate I think you should debug the Create API. Here is a way to debug it and view and logs - https://github.com/AnomalyInnovations/serverless-stack-com/issues/28#issuecomment-297097300

Let me know if that makes sense.

jayair avatar May 24 '17 14:05 jayair

Hello again. When trying to do the deployment (serverless deploy) I got the following response:

Serverless: Packing external modules: babel-runtime@^6.23.0, uuid@^3.0.1
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (1.03 MB)...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
CloudFormation - UPDATE_IN_PROGRESS - AWS::CloudFormation::Stack - notes-app-api-prod
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - DeleteLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::Lambda::Permission - 2Underscorewk567VfjNLambdaPermissionApiGateway
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - UpdateLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::IAM::Role - IamRoleLambdaExecution
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - ListLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - GetLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - CreateLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - CREATE_FAILED - AWS::Lambda::Permission - 2Underscorewk567VfjNLambdaPermissionApiGateway
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - DeleteLogGroup
CloudFormation - CREATE_COMPLETE - AWS::Logs::LogGroup - DeleteLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::IAM::Role - IamRoleLambdaExecution
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - ListLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - GetLogGroup
CloudFormation - CREATE_IN_PROGRESS - AWS::Logs::LogGroup - UpdateLogGroup
CloudFormation - CREATE_FAILED - AWS::Logs::LogGroup - CreateLogGroup
CloudFormation - CREATE_COMPLETE - AWS::Logs::LogGroup - ListLogGroup
CloudFormation - CREATE_FAILED - AWS::Logs::LogGroup - GetLogGroup
CloudFormation - CREATE_FAILED - AWS::IAM::Role - IamRoleLambdaExecution
CloudFormation - CREATE_FAILED - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - CREATE_FAILED - AWS::Logs::LogGroup - UpdateLogGroup
CloudFormation - UPDATE_ROLLBACK_IN_PROGRESS - AWS::CloudFormation::Stack - notes-app-api-prod
CloudFormation - UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS - AWS::CloudFormation::Stack - notes-app-api-prod
CloudFormation - DELETE_IN_PROGRESS - AWS::Logs::LogGroup - GetLogGroup
CloudFormation - DELETE_IN_PROGRESS - AWS::Logs::LogGroup - ListLogGroup
CloudFormation - DELETE_IN_PROGRESS - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - DELETE_IN_PROGRESS - AWS::Logs::LogGroup - DeleteLogGroup
CloudFormation - DELETE_COMPLETE - AWS::Lambda::Permission - 2Underscorewk567VfjNLambdaPermissionApiGateway
CloudFormation - DELETE_IN_PROGRESS - AWS::Logs::LogGroup - UpdateLogGroup
CloudFormation - DELETE_IN_PROGRESS - AWS::IAM::Role - IamRoleLambdaExecution
CloudFormation - DELETE_IN_PROGRESS - AWS::Logs::LogGroup - CreateLogGroup
CloudFormation - DELETE_COMPLETE - AWS::Logs::LogGroup - GetLogGroup
CloudFormation - DELETE_COMPLETE - AWS::Logs::LogGroup - DeleteLogGroup
CloudFormation - DELETE_COMPLETE - AWS::Logs::LogGroup - ListLogGroup
CloudFormation - DELETE_COMPLETE - AWS::Logs::LogGroup - UpdateLogGroup
CloudFormation - DELETE_COMPLETE - AWS::ApiGateway::RestApi - ApiGatewayRestApi
CloudFormation - DELETE_COMPLETE - AWS::Logs::LogGroup - CreateLogGroup
CloudFormation - DELETE_COMPLETE - AWS::IAM::Role - IamRoleLambdaExecution
CloudFormation - UPDATE_ROLLBACK_COMPLETE - AWS::CloudFormation::Stack - notes-app-api-prod
Serverless: Deployment failed!
 
  Serverless Error ---------------------------------------
 
     An error occurred while provisioning your stack: 2Underscorewk567VfjNLambdaPermissionApiGateway
     - Unable to parse HTTP response content.
 
  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Forums:        forum.serverless.com
     Chat:          gitter.im/serverless/serverless
 
  Your Environment Information -----------------------------
     OS:                 darwin
     Node Version:       6.9.4
     Serverless Version: 1.13.2

This is my serverless.yml file:

service: notes-app-api

plugins:
  - serverless-webpack

custom:
  webpackIncludeModules: true

provider:
  name: aws
  runtime: nodejs6.10
  stage: prod
  region: us-east-2

  # 'iamRoleStatement' defines the permission policy for the Lambda function.
  # In this case Lambda functions are granted with permissions to access DynamoDB.
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:us-east-2:*:*"

functions:
  # Defines an HTTP API endpoint that calls the main function in create.js
  # - path: url path is /notes
  # - method: POST request
  # - cors: enabled CORS (Cross-Origin Resource Sharing) for browser cross
  #     domain api call
  # - authorizer: authenticate the api via Cognito User Pool. Update the 'arn'
  #     with your own User Pool ARN
  create:
    handler: create.main
    events:
      - http:
          path: notes
          method: post
          cors: true
          authorizer:
            arn: aws:cognito-idp:us-east-2:311966611455:userpool/us-east-2_wk567VfjN

  get:
    # Defines an HTTP API endpoint that calls the main function in get.js
    # - path: url path is /notes/{id}
    # - method: GET request
    handler: get.main
    events:
      - http:
          path: notes/{id}
          method: get
          cors: true
          authorizer:
            arn: aws:cognito-idp:us-east-2:311966611455:userpool/us-east-2_wk567VfjN

  list:
    # Defines an HTTP API endpoint that calls the main function in list.js
    # - path: url path is /notes
    # - method: GET request
    handler: list.main
    events:
      - http:
          path: notes
          method: get
          cors: true
          authorizer:
            arn: aws:cognito-idp:us-east-2:311966611455:userpool/us-east-2_wk567VfjN

  update:
    # Defines an HTTP API endpoint that calls the main function in update.js
    # - path: url path is /notes/{id}
    # - method: PUT request
    handler: update.main
    events:
      - http:
          path: notes/{id}
          method: put
          cors: true
          authorizer:
            arn: aws:cognito-idp:us-east-2:311966611455:userpool/us-east-2_wk567VfjN
  delete:
    # Defines an HTTP API endpoint that calls the main function in delete.js
    # - path: url path is /notes/{id}
    # - method: DELETE request
    handler: delete.main
    events:
      - http:
          path: notes/{id}
          method: delete
          cors: true
          authorizer:
            arn: aws:cognito-idp:us-east-2:311966611455:userpool/us-east-2_wk567VfjN

I have checked everything and I do not know where the error is. Can someone help me? Thank you very much!

martinsaporiti avatar May 29 '17 22:05 martinsaporiti

@martinsaporiti, the authorizer arn should start with arn: it should look something like

          authorizer:
            arn: arn:aws:cognito-idp:us-east-2:311966611455:userpool/us-east-2_wk567VfjN

fwang avatar May 30 '17 01:05 fwang

You are me hero @fwang! Thaks!!!

Serverless: Stack update finished...
Service Information
service: notes-app-api
stage: prod
region: us-east-2
api keys:
  None
endpoints:
  POST - https://omc6734xf9.execute-api.us-east-2.amazonaws.com/prod/notes
  GET - https://omc6734xf9.execute-api.us-east-2.amazonaws.com/prod/notes/{id}
  GET - https://omc6734xf9.execute-api.us-east-2.amazonaws.com/prod/notes
  PUT - https://omc6734xf9.execute-api.us-east-2.amazonaws.com/prod/notes/{id}
  DELETE - https://omc6734xf9.execute-api.us-east-2.amazonaws.com/prod/notes/{id}
functions:
  create: notes-app-api-prod-create
  get: notes-app-api-prod-get
  list: notes-app-api-prod-list
  update: notes-app-api-prod-update
  delete: notes-app-api-prod-delete

Stack Outputs
DeleteLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-2:311966611455:function:notes-app-api-prod-delete:1
CreateLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-2:311966611455:function:notes-app-api-prod-create:1
GetLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-2:311966611455:function:notes-app-api-prod-get:1
UpdateLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-2:311966611455:function:notes-app-api-prod-update:1
ListLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-2:311966611455:function:notes-app-api-prod-list:1
ServiceEndpoint: https://omc6734xf9.execute-api.us-east-2.amazonaws.com/prod
ServerlessDeploymentBucketName: notes-app-api-prod-serverlessdeploymentbucket-k0qhmr6n8ar1

Serverless: Removing old service versions...

martinsaporiti avatar May 30 '17 11:05 martinsaporiti

What does this line check for?

body = (body) ? JSON.stringify(body) : body;

ghost avatar Jul 03 '17 12:07 ghost

@petrovm We are checking if the body is passed in to the call. If it is then we JSON encode it and make a request with it.

jayair avatar Jul 03 '17 16:07 jayair

Hi, I was one of the unlucky ones who had to upgrade my API in the middle of the tutorial to use IAM to authenticate, instead of the arn. I looked at the changelog and did a new serverless deploy with the updated create/delete/get/list.js files + serverless.yml.

I am able to test the api with the apig-test command from the terminal and get a 200 response:

Authenticating with User Pool
Getting temporary credentials
Making API request
{ status: 200,
  statusText: 'OK',
  data: 
   { userId: 'us-east-1:7d88cdb0-5140-422f-9859-1d9afac66456',
     noteId: 'f2d07fc0-70ed-11e7-9cfd-8d2f175b56c4',
     content: 'hello world',
     attachment: 'hello.jpg',
     createdAt: 1500955294140 } }

But when I try to create a note from my /notes/new page, I get the following error: image

I've made sure to update the IAM policy to reflect the changes in the "create an identity pool" doc: https://github.com/AnomalyInnovations/serverless-stack-com/commit/717fcd89f33c6d7dd5ee5c2c2b5560136b115331#diff-8bccc23bba3c2ea21eb1a1cbea8b2ff3R80

Is there something I'm missing? Any help is very much appreciated :)

DreaminDani avatar Jul 25 '17 04:07 DreaminDani

@frittate - I am also getting an 'unable to fetch' error - what did you do to resolve your issue?

Update: I changed the URL in my config to /prod instead of /prod/ and this has issued a different error message, saying "Error: {status:false}

My repo is here: https://github.com/mikhaelbendavid/serverlessblog

Update - I updated the IAM role permissions to allow for put request to dynamo db requests! It works!

mikhael28 avatar Jul 25 '17 04:07 mikhael28

Nevermind, I forgot a closing "}" in this line: https://github.com/AnomalyInnovations/serverless-stack-demo-client/blob/call-the-create-api/src/libs/awsLib.js#L51

Also noticed that the compiler does not like sigV4Client.js since "Line 220 exceeds the maximum line length of 100": image

This can be fixed by simply breaking the line:

// If there is no body remove the content-type header
// so it is not included in SigV4 calculation

DreaminDani avatar Jul 25 '17 04:07 DreaminDani

@d3sandoval Thats interesting. Can I see what version Create React App are you using? create-react-app --version

jayair avatar Jul 25 '17 18:07 jayair

Hi all,

I'm getting things not imported - which libs are to be imported in awsLib.js?

./src/libs/awsLib.js
  Line 6:   'getAwsCredentials' is not defined  no-undef
  Line 10:  'AWS' is not defined                no-undef
  Line 11:  'AWS' is not defined                no-undef
  Line 12:  'AWS' is not defined                no-undef

anguaji avatar Aug 02 '17 10:08 anguaji

@anguaji Hmm it looks like you might have missed a step from the previous chapter? We install and import the AWS SDK in src/awsLib.js.

jayair avatar Aug 02 '17 22:08 jayair

Hi - I am receiving a 403 cors issue and cors is turned off. What could be the problem?

Fetch API cannot load https://*******.execute-api.us-west-2.amazonaws.com/prod/inventory. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

copperspeed avatar Aug 03 '17 07:08 copperspeed

@jayair thanks! I'd missed the definition between two hunks of code :)) thanks!

anguaji avatar Aug 03 '17 17:08 anguaji

@copperspeed Can you check the CloudWatch logs to see if you are getting anything there?

jayair avatar Aug 03 '17 17:08 jayair

I'm having the same CORS problem here, and my serverless.yml is the same of this https://github.com/AnomalyInnovations/serverless-stack-demo-api/blob/251d1defa682c70c7af770ba386b2069ef3eefda/serverless.yml#L42

ramonpm avatar Aug 11 '17 13:08 ramonpm