form-data post request using https in node.js - node.js

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

Related

Wait for http post to end using promise

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

Send POST Request via AWS Lambda in Node.js

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.

how to use async await with https post request

I am finding way out to use async / await with https post. Please help me out. I have posted my https post code snippet below.how do I use async await with this.
const https = require('https')
const data = JSON.stringify({
todo: 'Buy the milk'
})
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
Basically, you can write a function which will return a Promise and then you can use async/await with that function. Please see below:
const https = require('https')
const data = JSON.stringify({
todo: 'Buy the milk'
});
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
},
};
async function doSomethingUseful() {
// return the response
return await doRequest(options, data);
}
/**
* Do a request with options provided.
*
* #param {Object} options
* #param {Object} data
* #return {Promise} a promise of request
*/
function doRequest(options, data) {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let responseBody = '';
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
resolve(JSON.parse(responseBody));
});
});
req.on('error', (err) => {
reject(err);
});
req.write(data)
req.end();
});
}
I had this problem also, found this post, and used the solution from Rishikesh Darandale (here).
The await documentation states The await operator is used to wait for a Promise. Returning the promise from a function is not required. You can just create a promise and call await on it.
async function doPostToDoItem(myItem) {
const https = require('https')
const data = JSON.stringify({
todo: myItem
});
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
},
};
let p = new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let responseBody = '';
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
resolve(JSON.parse(responseBody));
});
});
req.on('error', (err) => {
reject(err);
});
req.write(data)
req.end();
});
return await p;
}
You can use async-await with Promises only and Node's core https module does not have build in promise support. So you first have to convert it into the promise format and then you can use async-await with it.
https://www.npmjs.com/package/request-promise
This module has converted the core http module into promisified version. You can use this.

In azure functions using javascript how to call send request to a endpoint

In Azure function how to call an API using javascript. The request is POST with the header.I tried to use XMLHttpRequest, but i got exception like this XMLHttpRequest is not defined.
var client = new XMLHttpRequest();
var authentication = 'Bearer ...'
var url = "http://example.com";
var data = '{.........}';
client.open("POST", url, true);
client.setRequestHeader('Authorization',authentication);
client.setRequestHeader('Content-Type', 'application/json');
client.send(data);
Any other method is there to achive this,
You can do it with a built-in http module (standard one for node.js):
var http = require('http');
module.exports= function (context) {
context.log('JavaScript HTTP trigger function processed a request.');
var options = {
host: 'example.com',
port: '80',
path: '/test',
method: 'POST'
};
// Set up the request
var req = http.request(options, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
context.res = body;
context.done();
});
}).on("error", (error) => {
context.log('error');
context.res = {
status: 500,
body: error
};
context.done();
});
req.end();
};
You can also use any other npm module like request if you install it into your Function App.

Does AWS Lambda (NodeJS) not allow http.request or https.request?

I am attempting to make a request to another API from a Lambda. I am finding that using the NodeJS http and https modules allow for GET requests but any others (e.g. POST) do not work; POST coincidentally is the only method I need to work for the service I am attempting to call.
Here is a working example of Lambda performing a GET and receiving a 200 response:
const https = require('https')
function handler(event, context, callback) {
const options = {
hostname: 'encrypted.google.com'
}
https
.get(options, (res) => {
console.log('statusCode:', res.statusCode);
res.on('end', callback.bind(null, null))
})
.on('error', callback);
}
exports.handler = handler
So that proves that he request is allowed. However, if the script attempts to make the same request using the .request() method of the https (or https) lib/module the request never finishes and the Lambda times out.
const https = require('https')
function handler(event, context, callback) {
const options = {
hostname: 'encrypted.google.com',
method: 'GET'
}
https
.request(options, (res) => {
console.log('statusCode:', res.statusCode);
res.on('end', callback.bind(null, null))
})
.on('error', callback);
}
exports.handler = handler
I don't know what I am doing wrong. The call https.request() silently fails - doesn't throw an error - and nothing is reported in the log.
The problem was that I was never completing the request with req.end().
const https = require('https')
function handler(event, context, callback) {
const options = {
hostname: 'encrypted.google.com',
method: 'GET'
}
https
.request(options, (res) => {
console.log('statusCode:', res.statusCode);
res.on('end', callback.bind(null, null))
})
.on('error', callback)
.end(); // <--- The important missing piece!
}
exports.handler = handler
Please try this one if your API is HTTPS,
var url = 'HTTPS URL HERE';
var req = https.get(url, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk
});
res.on("end", () => {
var result = JSON.parse(body);
callBack(result)
});
}).on("error", (error) => {
callBack(err);
});
}
And if it is HTTP then,
var url = 'HTTP URL HERE';
var req = http.get(url, (res) => {
var body = "";
res.on("data", (chunk) => {
body += chunk
});
res.on("end", () => {
var result = JSON.parse(body);
callBack(result)
});
}).on("error", (error) => {
callBack(err);
});
}
Please don't fogot to add package require('https') / require('http')
The POST method is done by the request method.
This is the lambda code:
const https = require('https');
const options = {
hostname: 'Your host name',
path: '/api/v1/Login/Login',
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body : JSON.stringify({
'email': 'hassan.uzair9#gmail.com',
'password': 'Asdf1234.',
})
};
var result;
try{
result = await https.request(options);
console.log("result.....",result);
}catch(err){
console.log("err......",err);
}

Resources