Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to send response from a function or get the response? (node.js)

I am using a 3rd party sms service which I want to use in a different file. When I hit the api url I want to send the server response from the 3rd party api. How may I do this?

app.js

app.get('/sendansms', (req, res) => {
  let response = sendSms(res);
  console.log( "is response     ", response);
  res.send(response)
})

smsservice.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var request = require("request");

module.exports.sendSms = (params) => {
    var options = {
      'method': 'POST',
      'url': 'https://smsplus.xxxxxxx.com/api/v3/send-sms',
      'headers': {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        "api_token": "xxxxx-xxxxx-xxxxx-xxxxx",
        "sid": "xxxxxx",
        "msisdn": "xxxxxx",
        "sms": "Test SMS",
        "csms_id": "xxxxxxx"
      })
    
    };
    request(options, function (error, response) {
      if (error) throw new Error(error);
      console.log(response.body);
    });
};

>Solution :

you need to make your sendSms function promise base in order to return promise and in your route function you need to make function async to await for that promise…

in your app

app.get('/sendansms', async(req, res) => {   
    let response = await sendSms(req);   
    console.log( "is response     ", response);
    res.send(response) 
})

smsservice.js

var request = require("request");

odule.exports.sendSms = (params) => {
   return new Promise((resolve, reject)=> {
      try {
       var options = {
      'method': 'POST',
      'url': 'https://smsplus.xxxxxxx.com/api/v3/send-sms',
      'headers': {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        "api_token": "xxxxx-xxxxx-xxxxx-xxxxx",
        "sid": "xxxxxx",
        "msisdn": "xxxxxx",
        "sms": "Test SMS",
        "csms_id": "xxxxxxx"
      })
    
    };
    request(options, function (error, response) {
      if (error) throw new Error(error);
      console.log(response.body);
       return resolve(response.body);
    });
      } catch(e) {
        return reject(e)
     }

})
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading