pirple / The-NodeJS-Master-Class

Code samples for the Node.js Master Class
1.33k stars 1.21k forks source link

Connect to nexmo api #18

Closed i-coderdev closed 5 years ago

i-coderdev commented 5 years ago

How can I connect to nexmo SMS API, I have some errors with my code

const https = require('https'); const queryString = require('querystring');

function sendNexmoSms() { const payload = { to: '+91...', from: 'NEXMO', text: 'HELLO, I AM NEXMO DEMO SMS !' }; const stringPayload = queryString.stringify(payload); // console.log(stringPayload); const requestOptions = { protocol: 'https:', hostname: 'rest.nexmo.com', method: 'POST', path: '/sms/json', auth: 'api_key:api_secret', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(stringPayload) } }; const req = https.request(requestOptions, res => { const code = res.statusCode if (code == 200 || code == 201) { console.log('DONE'); } else { console.log('errors happend'); } }); req.on('error', e => console.log(e)); req.write(stringPayload); req.end(); }

sendNexmoSms();

i-coderdev commented 5 years ago

Problem solved:-

const https = require('https'); const queryString = require('querystring');

function sendNexmoSms() { const payload = { to: '+91...', from: 'NEXMO', text: 'HELLO, I AM NEXMO DEMO SMS !', api_key: '1c...', api_secret: '0Cg1...' }; const stringPayload = queryString.stringify(payload); // console.log(stringPayload); const requestOptions = { protocol: 'https:', hostname: 'rest.nexmo.com', method: 'POST', path: '/sms/json', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(stringPayload) } }; const req = https.request(requestOptions, res => { const code = res.statusCode if (code == 200 || code == 201) { console.log('DONE'); } else { console.log('errors happend', code); } }); req.on('error', e => console.log(e)); req.write(stringPayload); req.end(); }

sendNexmoSms();

It's working... My little mistake.