I'm having trouble with converting Postman cURL to SSJS. My goal is to build a cloudpage to make an API call to an external platform to create records, but somehow my SSJS code does not work. Here is the cURL that works in Postman:
curl --location --request POST 'https://www.example.com/api/user/create' \
--header 'Token: tokenvalue' \
--header 'Username: usernamevalue' \
--header 'Content-Type: application/json' \
--data-raw '{
"field1": "value1",
"field2": "value2",
"field3": "value3",
}'
And this is my SSJS code:
<script language="javascript" runat="server">
Platform.Load('Core','1.1.5');
var url = 'https://www.example.com/api/user/create' ;
var token = "tokenvalue";
var username = "usernamevalue";
var payload = {}
payload.field1= "value1";
payload.field2= "value2";
payload.field3= "value3";
function createUser(url, payload, token, username) {
var req = new Script.Util.HttpRequest(url);
req.emptyContentHandling = 0;
req.retries = 2;
req.continueOnError = false;
req.contentType = "application/json"
req.setHeader("Token", token);
req.setHeader("Username", username);
req.method = "POST";
req.postData = payload;
var resp = req.send();
var resultStr = String(resp.content);
var resultJSON = Platform.Function.ParseJSON(String(resp.content));
return resultStr;
}
var response = createUser(url, payload, token, username);
Write('Response: ' + response);
</script>
I'm clearly missing something but I'm unable to detect it. If I set req.continueOnError to true, nothing happens and if I set it to false and preview this code in an email, I get 'The remote server returned an error: (411) Length Required.' as an error. Could someone help me with this, please? Is this happening because of Headers?
UPDATE 1
Changed "req.postData = payload;" to "req.postData = Stringify(payload);" and now I'm getting: "The remote server returned an error: (400) Bad Request".
UPDATE 2
Updated "return resultStr;" to "return resultJSON;" and still getting the same error
req.postData = Stringify(payload);
resultStr
and it's not the one was parsed, change it to return theresultJSON