Convert request.js to axios (Vonage api)

Viewed 918

I'm working on a messenger project with Vonage api. This code works well but I tried to convert it to axios instead of 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);

This is axios version with same request:

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

And it doesn't work. I tried also

  1. axios.post()
  2. JSON.stringify for body
2 Answers

The axios property to set the body data is "data", not "body". This has caught me out before. Please try the below with some console logging to check the correct request is being sent:

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 support sent me this code and it worked(No body or data)

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