Vincent Claes
Vincent Claes

Reputation: 4788

Serverless invoke works but curl gives error

I have a serverless function, you can find the code below, and this function is deployed on aws lambda using the serverless framework. from within this function i call an external web api.

When i do serverless invoke -f my_func i get the expected response. but if i run a curl command it fails and i get {"message": "Internal server error"}

this is my curl command:

   curl -X GET \
  https://0wb3echzu8.execute-api.us-east-1.amazonaws.com/dev/my_func \
  -H 'cache-control: no-cache' \
  -H 'postman-token: 1fc551c0-7010-e1e3-7287-6a0d82d1e91a'

this is my code:

var request = require("request");
var options = { method: 'GET',
  url: 'https://api.coinmarketcap.com/v2/listings/',
  headers:
   { 'postman-token': '090e284e-62ad-29f0-0f10-92ae14656a37',
     'cache-control': 'no-cache' } };
module.exports.my_func = (event, context, callback) => {
  request(options, function (error, response, body) {
      if (error) { console.log(error); callback(null, error) }
      console.log(body)
      callback(null, body)
  });
};

this is the serverless.yml file:

service: aws-nodejs
app: sonarsic
tenant: vincent

provider:
  name: aws
  runtime: nodejs6.10


functions:
  my_func:
    handler: handler.my_func
    events:
      - http:
          path: my_func
          method: get
          cors: true

It must have to do something with the calling of the web api in my function. if i don't call a web api it works fine.

If I check the logs via serverless logs -f my_func i only get the logs of the calls that worked using serverless invoke.

what can i do to find out what is going wrong inside my function when making a curl command?

adding cors:true to the http section does not solve the problem

cloudwatch is attached to aws lambda but it seems there is nothing written to: enter image description here

Upvotes: 1

Views: 1420

Answers (1)

Theo
Theo

Reputation: 2042

After some discussion on chat, we discovered that statusCode on the response body is missing

let request = require('request');
let options = {
  method: 'GET',
  url: 'https://api.coinmarketcap.com/v2/listings/',
  headers: {
    'postman-token': '090e284e-62ad-29f0-0f10-92ae14656a37',
    'cache-control': 'no-cache',
  },
};
module.exports.my_func = (event, context, callback) => {
  request(options, (error, response, body) => {
      if (error) { console.log(error); callback(null, error) }
      console.log(body)
      callback(null, { body, statusCode: 200 }) // response statusCode added
  });
};

Upvotes: 2

Related Questions