0

Here is my curl request. I am trying to convert this to nodemon.js request.

    curl--location 'https://conversations.messagebird.com/v1/conversations/start' \
    --header 'Authorization: AccessKey Key' \
    --header 'Content-Type: application/json' \
    --data '{"to": "+919853092550",
    "type": "hsm",
    "channelId": "f10ea05178db478089117cc7cba79d5c",
    "content":
    {"hsm": 
    {"namespace": "92239cc8_406b_4bdf_aab5_b1c379b9b139",
    "templateName": "otp",
    "language": 
    {"policy": "deterministic","code": "en"},
    "params": [
        {"default": "123456"}
        ]
        }
        }}'

Here, this is how i converted this.

    var headers = {
      Authorization: "AccessKey Key",
      "Content-Type": "application/json",
    };
    var dataString = `{
      "to": ${number},
      "type": "hsm",
      "channelId": "f10ea05178db478089117cc7cba79d5c",
      "content": {
        "hsm": {
          "namespace": "92239cc8_406b_4bdf_aab5_b1c379b9b139",
          "templateName": "otp",
          "language": { "policy": "deterministic", "code": "en" },
          "params": [{ "default": ${otp} }],
        },
      },
    }`;
    var options = {
      url: "https://conversations.messagebird.com/v1/conversations/start",
      method: "POST",
      headers: headers,
      body: dataString,
    };
    request.post(options, function (error, response, body) {
      if (error) console.log(error);
      console.log(body);
    });
    

I am getting below error. I tried by doing JSON.stringify still not working.

{ "errors": [{ "code": 21, "description": "JSON is not a valid format" }] }

Please take a look how to solve this issue

  • Does this answer your question? [send Content-Type: application/json post with node.js](https://stackoverflow.com/questions/8675688/send-content-type-application-json-post-with-node-js). Specifically, [this answer](https://stackoverflow.com/a/49189039/283366) – Phil May 03 '23 at 07:00

1 Answers1

-1

In the body, you are not passing the JSON object. If you use ` sign then it will be considered as a string instead of a JSON object.

You can replace your dataString variable with below given code.

var dataString = {
  "to": number,
  "type": "hsm",
  "channelId": "f10ea05178db478089117cc7cba79d5c",
  "content": {
    "hsm": {
      "namespace": "92239cc8_406b_4bdf_aab5_b1c379b9b139",
      "templateName": "otp",
      "language": { "policy": "deterministic", "code": "en" },
      "params": [{ "default": otp }],
    },
  },
};

To verify whether you have correctly converted CURL to Request, you can use given link.