node.js将curl转换为request

xuo3flqw  于 2023-05-06  发布在  Node.js
关注(0)|答案(1)|浏览(165)

这是我的curl请求。我正在尝试将此转换为nodemon.js请求。

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"}
        ]
        }
        }}'

这是我如何转换的。

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);
    });

我在错误下面。我试着用JSON.stringify还是不行。

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

请看一下如何解决这个问题

b1uwtaje

b1uwtaje1#

在body中,您没有传递JSON对象。如果你使用` sign,那么它将被视为字符串而不是JSON对象。
你可以用下面的代码替换你的dataString变量。

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 }],
    },
  },
};

要验证您是否正确将CURL转换为Request,您可以使用given link .

相关问题