将 request.js 转换为 axios (Vonage api)

Convert request.js to axios (Vonage api)

我正在使用 Vonage api 开发 Messenger 项目。 此代码运行良好,但我尝试将其转换为 axios 而不是 require.js

var request = require("request");
const data = JSON.stringify({
  from: { type: "messenger", id: process.env.BOT_ID },
  to: { type: "messenger", id: process.env.USER_ID },
  message: {
    content: {
      type: "text",
      text: "Hi There!",
    },
  },
});
var options = {
  url: "https://messages-sandbox.nexmo.com/v0.1/messages",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  body: data,
  auth: {
    user: process.env.API_KEY,
    pass: process.env.API_SECRET_KEY,
  },
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
}

request(options, callback);

这是具有相同请求的 axios 版本:

axios({
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  body: {
    from: { type: "messenger", id: process.env.BOT_ID },
    to: { type: "messenger", id: process.env.USER_ID },
    message: {
      content: {
        type: "text",
        text:
          "Hi There!"
      },
    },
  },
  auth: {
    user: process.env.API_KEY,
    pass: process.env.API_SECRET_KEY,
  },
  url: "https://messages-sandbox.nexmo.com/v0.1/messages",
});

而且它不起作用。 我也试过了

  1. axios.post()
  2. JSON.stringify 正文

设置正文数据的axios 属性是“数据”,而不是“正文”。这让我很困惑。请尝试使用以下控制台日志记录来检查是否发送了正确的请求:

axios({
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  data: {
    from: { type: "messenger", id: process.env.BOT_ID },
    to: { type: "messenger", id: process.env.USER_ID },
    message: {
      content: {
        type: "text",
        text:
          "Hi There!"
      },
    },
  },
  auth: {
    user: process.env.API_KEY,
    pass: process.env.API_SECRET_KEY,
  },
  url: "https://messages-sandbox.nexmo.com/v0.1/messages",
});

Vonage 支持人员向我发送了这段代码并且它有效(没有正文或数据)

axios
  .post(
    "https://messages-sandbox.nexmo.com/v0.1/messages",
    {
      from: { type: "messenger", id: "107083064136738" },
      to: { type: "messenger", id: "3958866477502819" },
      message: {
        content: {
          type: "text",
          text: "You should havee ",
        },
      },
    },
    {
      auth: {
        username: "5aa06d41",
        password: "FMqffmop1GB64X58",
      },
    }
  )
  .then(function (response) {
    console.log("Status: " + response.status);
    console.log(response.data);
  })
  .catch(function (error) {
    console.error(error);
  });