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

Time:10-11

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

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

CodePudding user response:

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

})
}

  • Related