I want to send a POST Request to Twilio when an Intent is called from my Alexa Skill. When testing the Code, there are no errors, but the Request doesn't seem to go through. Testing the POST Request in Postman works.
function postToTwilio() {
var http = require("https");
var postData = JSON.stringify({
'To' : '1234567',
'From': '1234546',
'Url': 'https://handler.twilio.com/twiml/blablabla',
});
var options = {
"method": "POST",
"hostname": "https://api.twilio.com",
"path": "/12344/Accounts/blablablablba/Calls.json",
"headers": {
"Authorization": "Basic blblablablablabla",
"Content-Type": "application/x-www-form-urlencoded",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(postData);
req.end();
}
First of all, a request is a async call so you need to make alexa wait for the response.
To do that, you need to use async await process and using promises.
var postData = JSON.stringify({
'To' : '1234567',
'From': '1234546',
'Url': 'https://handler.twilio.com/twiml/blablabla',
});
var options = {
"method": "POST",
"hostname": "https://api.twilio.com",
"path": "/12344/Accounts/blablablablba/Calls.json",
"headers": {
"Authorization": "Basic blblablablablabla",
"Content-Type": "application/x-www-form-urlencoded",
}
};
function get(options) {
return new Promise(((resolve, reject) => {
const request = https.request(options, (response) => {
response.setEncoding('utf8');
let returnData = '';
if (response.statusCode < 200 || response.statusCode >= 300) {
return reject(new Error(`${response.statusCode}: ${response.req.getHeader('host')} ${response.req.path}`));
}
response.on('data', (chunk) => {
returnData += chunk;
});
response.on('end', () => {
resolve(JSON.parse(returnData));
});
response.on('error', (error) => {
reject(error);
});
});
request.write(postData)
request.end();
}));
}
Then, when you call this get function:
let response = await get(options)
I haven't tested as a whole but that is the base skeleton.
Let me know if that works.
Related
How can I send form-data post request using http package?
I have working code with "request" package:
let result = await request({
url: getTokenURL,
method: "POST",
form: `login=${login}&password=${password}`
});
but I want do the same with native http
trying this:
let getToken = function(url, login, password){
return new Promise((resolve, reject) => {
let getTokenURL = `${url}`;
console.log(`requesting ${getTokenURL}`);
let httpRequest = http.request({
uri: getTokenURL,
port: 80,
method: 'POST',
form: `login=${login}&password=${password}`
}, (response) => {
let body = '';
response.on('data', (chunk) => {
body += chunk;
});
response.on('end', () => {
console.log(body);
return resolve(body);
});
});
});
}
but it's raising an error
I am learning to use http post and trying to wait for it to end using promise. But I can't get it to work, please help:
var http = require('http');
const auth = () => {
var post_data = JSON.stringify({
"username": "aaa",
"password": "bbb"
});
const options = {
host: 'http://1.1.1.1',
path: '/v1/authentication',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
}
};
const req = http.request(options, (res) => {
res.setEncoding('utf8');
var body = '';
res.on('data', d => {
body += chunk;
});
res.on('end', function() {
console.log("Response body", body);
});
});
req.on('error', error => {
console.error("error", error);
});
req.write(post_data)
req.end();
return Promise.resolve("!!");
};
exports.helloWorld = (req, res) => {
let message = req.query.message || req.body.message || 'Hello World!';
return auth().then((res)=>{
res.status(200).send(res);
});
};
Entry point is the hellWorld function. What should I do to wait for the http post to finish and get the response result using promise?
here i did some for get api call.
try {
const auth = () => {
return new Promise((resolve, reject) => {
const options = {
host: 'api.github.com',
path: '/orgs/nodejs',
port: 443,
method: 'GET',
headers: {
'User-Agent': 'request'
}
};
const req = https.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', d => {
resolve(d)
});
});
req.on('error', error => {
console.error("error", error);
});
req.end();
})
};
const data = await auth()
console.log('should execute first', data)
console.log('should executed after http call')
} catch (e) {
console.log(e)
}
you can modify above code with your, just you have to wrap your http call inside Promises.
comment down if any its a solution, and mark as a solution
I have an azure function with this line of code.
var myReq = https.request(options, function(res) {
context.log('STATUS: ' + res.statusCode);
context.log('HEADERS: ' + JSON.stringify(res.headers));
body += res.statusCode
res.on('data', function (chunk) {
context.log('BODY: ' + chunk);
});
});
myReq.on('error', function(e) {
context.log('problem with request: ' + e.message);
});
myReq.write(postData);
myReq.end();
But my code seems to just skip this part of code, with no errors. I am new to Azure and node.js so I might have missed some basic parts in setting this up.
Any ideas?
Edit:
Here is my full code
const https = require('https');
const querystring = require('querystring');
module.exports = async function (context, req) {
if (req.query.accessCode || (req.body && req.body.accessCode)) {
context.log('JavaScript HTTP trigger function processed a request.');
var options = {
host: 'httpbin.org',
port: 80,
path: '/post',
method: 'POST'
};
var postData = querystring.stringify({
client_id : '1234',
client_secret: 'xyz',
code: req.query.accessCode
});
var body = "";
var myReq = https.request(options, function(res) {
context.log('STATUS: ' + res.statusCode);
context.log('HEADERS: ' + JSON.stringify(res.headers));
body += res.statusCode
res.on('data', function (chunk) {
context.log('BODY: ' + chunk);
});
});
myReq.on('error', function(e) {
context.log('problem with request: ' + e.message);
});
myReq.write(postData);
myReq.end();
context.log("help");
context.res = {
status: 200,
body: "Hello " + (body)
};
} else {
context.res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
};
Ideally it should work. You can also try using request module like below
const request = require('request');
request('http://www.google.com', function (error, response, body) {
console.error('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
Try and see if it helps.
Solved by doing await properly. Used this as guide.
var https = require('https');
var util = require('util');
const querystring = require('querystring');
var request = require('request')
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
/*if (req.query.name || (req.body && req.body.name)) {*/
var getOptions = {
contentType: 'application/json',
headers: {
'Authorization': <bearer_token>
},
};
var postData = {
"key": "value"
};
var postOptions = {
method: 'post',
body: postData,
json: true,
url: <post_url>,
headers: {
'Authorization': <bearer_token>
},
};
try{
var httpPost = await HttpPostFunction(context, postOptions);
var httpGet = await HttpGetFunction(context, <get_url>, getOptions);
return {
res: httpPost
};
}catch(err){
//handle errr
console.log(err);
};
};
async function HttpPostFunction(context, options) {
context.log("Starting HTTP Post Call");
return new Promise((resolve, reject) => {
var data = '';
request(options, function (err, res, body) {
if (err) {
console.error('error posting json: ', err)
reject(err)
}
var headers = res.headers;
var statusCode = res.statusCode;
//context.log('headers: ', headers);
//context.log('statusCode: ', statusCode);
//context.log('body: ', body);
resolve(body);
})
});
};
async function HttpGetFunction(context, url, options) {
context.log("Starting HTTP Get Call");
return new Promise((resolve, reject) => {
var data = '';
https.get(url, options, (resp) => {
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
})
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: " + err.message);
reject(err.message);
});
});
};
I have trying to send post call on https://api-mean.herokuapp.com/api/contacts with following data:
{
"name": "Test",
"email": "test#xxxx.in",
"phone": "989898xxxx"
}
But not get any response.
I have also tried it with postman it working fine. I have get response in postman.
I am using following nodejs code:
var postData = querystring.stringify({
"name": "Test",
"email": "test#xxxx.in",
"phone": "989898xxxx"
});
var options = {
hostname: 'https://api-mean.herokuapp.com',
path: '/api/contacts',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
var req = http.request(options, function (res) {
var output = '';
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', function () {
var obj = JSON.parse(output.trim());
console.log('working = ', obj);
resolve(obj);
});
});
req.on('error', function (e) {
console.error(e);
});
req.write(postData);
req.end();
Am I something missing?
How to send http post call from node server?
I recommend you to use the request module to make things easier.
var request=require('request');
var json = {
"name": "Test",
"email": "test#xxxx.in",
"phone": "989898xxxx"
};
var options = {
url: 'https://api-mean.herokuapp.com/api/contacts',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: json
};
request(options, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
console.log(body);
}
});
For sending HTTP-POST call from nodejs, you might need to use the request module
Sample:
var request = require('request');
request({
url: "some site",
method: "POST",
headers: {
// header info - in case of authentication enabled
},
json:{
// body goes here
}, function(err, res, body){
if(!err){
// do your thing
}else{
// handle error
}
});
I am trying to connect to mavenlink using node, but i keep getting an oauth2 validation error. Every solution online pertains to token generation for many users, but i just need to manipulate the data for use in an internal app. Does anyone have an example of oauth2 authentication for one user?
oauth2 authentication in this case is achieved with "Authorization": "Bearer key".toString('base64') inside of the headers option.
var https = require("https");
function printError (error) {
console.error(error);
}
key = 'oauth2 token';
var options = {
host: 'api.mavenlink.com',
path: '/api/v1/workspaces.json',
method: 'GET',
headers: {
"Content-type": "application/json",
"Authorization": "Bearer key".toString('base64')
}
};
var body = "";
var req = https.request(options, (res) => {
console.log('statusCode: ', res.statusCode);
console.log('headers: ', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
res.on('data', function (chunks){
body += chunks;
});
res.on('end', function() {
if(res.statusCode == 200) {
try
{
//parse data
var massData = JSON.parse(body);
console.log(body);
} catch(error) {
//parse error
printError(error);
}
}
});
});