Home > Mobile >  In Lambda with Node.js and Axios, how do I pass a log entry as a variable to another axios function
In Lambda with Node.js and Axios, how do I pass a log entry as a variable to another axios function

Time:01-21

I'm writing a Lambda function using Axios to make calls to my external API server. My goal is to perform two steps:

Step one is to authenticate my user to retrieve an access token. Step two is to use that access token in order to GET server alarms.

The first part axios.post works and the access token shows in the logs. I cannot seem to set that as a variable to pass to the second step. If I have it as two separate functions it does not know what the token value is, so I was trying to potentially nest the axios functions to see if that could read the value. I now receive a TypeError: (intermediate value)}.then is not a function.

Here's where I stand with the the Lambda function. I appreciate the help!

exports.handler = function(event, context, callback) {

    const apiUser = process.env.api_user;
    const apiPwd = process.env.api_pwd;

    var apiURL = "https://external-api-server.com:5454";

    var axios = require('axios');
    var userInfo = JSON.stringify({
        "user": {
            "admin_user": apiUser,
            "admin_pwd": apiPwd
        }
    });

    var head = {
        headers: {
            'Content-Type': 'application/json'
        },
    };

    return axios.post(apiURL   '/api/auth/', userInfo, head)
        .then(function(resp) {
            console.log(JSON.stringify(resp.data.access_token));
            var setToken = resp.data.access_token;

            return axios.get(apiURL   '/api/alarms?summary=&crit=&maj=&date=', {
                headers: {
                    'x-access-token': setToken,
                    'x-key': apiUser
                }
                .then(function(alarmResp) {
                    console.log(JSON.stringify(alarmResp.data));
                })
                .catch(function(err) {
                    console.log(err);
                })
            });
        });
};

CodePudding user response:

I figured it out. It was missing a parentheses after the headers and just before .then(function(alarmResp). Here's the corrected formatting of the function:

...
      return axios.get(apiURL   '/api/alarms?summary=&crit=&maj=&date=', {
              headers: {
                  'x-access-token': setToken,
                  'x-key': apiUser
              }
          })   // <------ added parentheses here
          .then(function(alarmResp) {
              console.log(JSON.stringify(alarmResp.data));
          })
          .catch(function(err) {
              console.log(err);
          });   // <------ moved semicolon here
    });
...
  •  Tags:  
  • Related