API call - building payload

Still learning and struggling with some basics.

I am building a call to an api in a function node. I have a hardcoded version of the call, within the code, so I can prove a call works and test my building of the data quickly (comment either in/out)

var todayd = new Date();
var yesterdayd = new Date();
yesterdayd.setDate(yesterdayd.getDate() - 1);
todayd = (todayd.getFullYear() + '-' + ('00' + (todayd.getMonth() + 1)).slice(-2) + '-' + ('00' + todayd.getDate()).slice(-2) + 'T00:00:00');
yesterdayd = (yesterdayd.getFullYear() + '-' + ('00' + (yesterdayd.getMonth() + 1)).slice(-2) + '-' + ('00' + yesterdayd.getDate()).slice(-2) + 'T00:00:00');

var message = 'from:"' + yesterdayd + '",';
message+= 'to:"' + todayd + '",';
message += '   period: "P1W",function: "sum"'
msg.payload = {
/* hardcoded works  
"from": "2022-10-10T00:00:00",
    "to": "2022-10-11T00:00:00",
    "period": "P1W",
    "function": "sum"
*/
/* does not work */   
message

    }
msg.headers = {};
msg.headers['accept'] = "application/json";
msg.headers['token'] = global.get("hildebrand_glowmrkt_token");
msg.headers['applicationId'] = global.get("hildebrand_glowmarkt_applicationId");
msg.url = "https://api.glowmarkt.com/api/v0-1/resource/" + global.get("hildebrand_glowmrkt_resourceIdAMRAPI") + "/readings?";
return msg;

Building the code is failing. The difference between the payloads is below:

Hardcoded (and works):

from: "2022-10-09T00:00:00"
to: "2022-10-11T00:00:00"
period: "P1W"
function: "sum"

My attempt at building it:

message: "from:"2022-10-10T00:00:00",to:"2022-10-11T00:00:00",   period: "P1W",function: "sum""

I understand the reason why my version is invalid as it is clearly treating the payload as a "message" variable. However, I don't know how to code this so that it is simply the 4 variables in the object created.

This is because you have output your code as a string and not as an object.

You need

msg.payload = {
   from: yesterdayd,
   to: todayd,
   period: "P1W",
   function: "sum",
}

Thanks so much.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.