0

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

6
  • Try to convert the JSON to string, I would try this to see if it works req.postData = Stringify(payload);
    – Duc Le
    Jan 26 at 0:33
  • Ah, I forgot to add Stringfy there, thanks! I tried that and now I got "The remote server returned an error: (400) Bad Request." Do you spot any errors or do you have any recommendations?
    – Baran Sen
    Jan 26 at 8:59
  • It seems the function will return resultStr and it's not the one was parsed, change it to return the resultJSON
    – Duc Le
    Jan 26 at 9:42
  • You're right, that part was wrong, thanks! Updated "return resultStr;" to "return resultJSON;" and still getting the same error unfortunately
    – Baran Sen
    Jan 26 at 10:28
  • Can you post the response here from what you get in your Postman?
    – Duc Le
    Jan 26 at 11:36

0

You must log in to answer this question.