Recently discovered AWS and i'm doing great, today i want to send a test notification to my iPhone X. I'm trying to do so when my database get's an update, Using the dynamoDB trigger blueprint.
Regular Notifications Delivered on the Dashboard works
This is what i have tried to so far, I'm neither getting the rep console log on CloudWatch nor an error.
console.log('Loading function');
const async = require('async');
const https = require('https');
exports.handler = async (event, context) => {
console.log('Received event:', JSON.stringify(event, null, 2));
const name = "35b83a10-9f46-4c2c-95e1-22c6d40005a8";
var message = {
app_id: "appid",
contents: {"en": "Your order has arrived at your doorstep"},
include_player_ids: ["14894201-64f7-486a-b65e-6beedf5880f1",name,"8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"]
};
sendNotification(message);
console.log("Activation change detected. message sent");
return `Successfully processed ${event.Records.length} records.`;
};
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic hidden_in_question"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("rep:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
I do not get the message on my iPhone. What seems to be the problem here?
But getting:
Activation change detected. message sent
on the console.
HTTP request is an async action which means you need to wait for the response, but in your case you are returning from the handler just after calling the function.
In order to fix this you need to wait for http request to finish before returning from handler. The following method assumes that you are using nodejs v8.x.
const https = require('https');
exports.handler = async (event, context) => {
console.log('Received event:', JSON.stringify(event, null, 2));
const name = "35b83a10-9f46-4c2c-95e1-22c6d40005a8";
var message = {
app_id: "appid",
contents: {"en": "Your order has arrived at your doorstep"},
include_player_ids: ["14894201-64f7-486a-b65e-6beedf5880f1",name,"8e0f21fa-9a5a-4ae7-a9a6-ca1f24294b86"]
};
await sendNotification(message);
console.log("Activation change detected. message sent");
return `Successfully processed ${event.Records.length} records.`;
};
var sendNotification = function(data) {
return new Promise(function(resolve, reject) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic hidden_in_question"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("rep:");
console.log(JSON.parse(data));
});
res.on('end', resolve);
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
reject(e);
});
req.write(JSON.stringify(data));
req.end();
});
}
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (body) {
console.log('Body: ' + body);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(data);
req.end();
Related
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
const http = require('http');
exports.handler = function (event, context, callback) {
console.log(event);
var data = {
'name': 'test'
};
var url = "http://**************.com";
function sendFileToUrl(url, data, context, callback) {
console.log('Sending File to the URL:' + url);
if (url && data && context) {
if (context) {
setInterval(function () { }, 1000);
context.callbackWaitsForEmptyEventLoop = false;
}
return http.post(url, JSON.stringify(data)).then(function (res) {
console.log("Data Sent & response: " + res.statusCode);
callback(null, 'success msg');
}).on('error', function (e) {
console.log("Could not send the data & error: " + e.message);
callback(new Error('failure'));
});
}
}
return sendFileToUrl(url, data, context, callback);
};
I am trying to make a http post request from lambda. Sending the data to the specified URL. But it is being asynchronous and gives a response message null
It is not printing the message "Data sent".
How to get this done? Thanks in advance
Try to change your code like this:
const http = require('http');
exports.handler = function (event, context, callback) {
console.log(event);
var data = JSON.stringify({
'name': 'test'
});
const options = {
hostname: 'example.com',
path: '/path-to-resource',
port: 80,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
function sendFileToUrl(options, data, callback) {
console.log('Sending File to the URL:' + url);
if (url && data) {
const req = http.request(url, JSON.stringify(data)).then(function (res) {
console.log("Data Sent & response: " + res.statusCode);
callback(null, 'success msg');
});
req.on('error', function (e) {
console.log("Could not send the data & error: " + e.message);
callback(new Error('failure'));
});
req.write(data);
req.end();
}
}
sendFileToUrl(options, data, callback);
};
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
[EDIT]
I figured it out. The code ends up like this:
//getTrelloJSON.js
var request = require('request');
'use strict';
function getProjJSON(requestURL, callback){
request.get({
url: requestURL,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
callback(data);
}
});
}
module.exports.getProjJSON = getProjJSON;
And
//showData.js
var getJSON = require('./getTrelloJSON');
getJSON.getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json', (result) => {
var lists = result.lists;
console.log(lists);
});
I run node showData.js and it gets the json and then I can manipulate it as needed. I printed just to show it works.
[EDIT END]
I'm new to node.js and I am facing a noob problem.
This code is supposed to request a JSON from a public trello board and return an object with a section of trello's json (lists section).
The first console.log() does not work but the second does.
How do I make it wait for the completion of getProjJSON() before printing it?
var request = require('request');
'use strict';
//it fails
console.log(getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json'));
function getProjJSON(requestURL){
request.get({
url: requestURL,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
//it works
console.log(data.lists);
return data.lists;
}
});
}
Node.js is all about callbacks.
And here you just not register the callbacks for data.
var client = require('http');
var options = {
hostname: 'host.tld',
path: '/{uri}',
method: 'GET', //POST,PUT,DELETE etc
port: 80,
headers: {} //
};
//handle request;
pRequest = client.request(options, function(response){
console.log("Code: "+response.statusCode+ "\n Headers: "+response.headers);
response.on('data', function (chunk) {
console.log(chunk);
});
response.on('end',function(){
console.log("\nResponse ended\n");
});
response.on('error', function(err){
console.log("Error Occurred: "+err.message);
});
});
or here is a full example, hope this solve your problem
const postData = querystring.stringify({
'msg' : 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`res_code: ${res.statusCode}`);
console.log(`res_header: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`res_data: ${chunk}`);
});
res.on('end', () => {
console.log('end of response');
});
});
req.on('error', (e) => {
console.error(`response error ${e.message}`);
});
//write back
req.write(postData);
req.end();
It's giving unauthorized as result error even when I pass the bearer token in Node.js application.
function getUser(authData){
var postData = querystring.stringify({ authorization: authData });
var options = {
host: 'pole.auth0.com',
method: 'GET',
path: '/userinfo'
};
//make request
httpsRequest(postData, options)
.then(function(result) {
// success
res.status(201).send({ 'success': true });
}, function(err) {
res.status(500).send({ 'success': false, 'reasonCode': "Internal error." });
});
};
Helper function:
function httpsRequest (data, options) {
return new Promise(function (resolve, reject) {
var req = https.request(options, function (res) {
var result = '';
console.log(options);
res.on('data', function (chunk) {
result += chunk;
});
res.on('end', function () {
console.log("https end result - " + result);
resolve(result);
});
res.on('error', function (err) {
reject(err);
})
});
// req error
req.on('error', function (err) {
reject(err);
});
//send request witht the postData form
req.write(data);
req.end();
});
}
The authData parameter has a string value like Bearer [token]. I'm using https.request to make the api request
Is there anything wrong on the code?
According to the /userinfo endpoint documentation you should be performing a GET HTTP request instead of a POST and additionally, you need to pass the access token in the Authorization header.
Update:
The problem is in how you're trying to pass the token in the authorization header.
You did not mentioned what you were using as HTTP client, but here's some sample code using request-promise as the Node HTTP client; this works fine.
var rp = require('request-promise');
var options = {
uri: 'https://[YOUR_TENANT].auth0.com/userinfo',
headers: {
'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]'
}
};
rp(options)
.then(function (info) {
console.log('User information:', info);
})
.catch(function (err) {
// API call failed...
});
Update 2:
With Node.js built-in HTTP client:
const https = require('https');
var options = {
hostname: '[YOUR_TENANT].auth0.com',
port: 443,
path: '/userinfo',
method: 'GET',
headers: {
'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]'
}
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.end();
req.on('error', (e) => {
console.error(e);
});
Again, the vital part is on how to pass the token in the correct header.
I am new to NodeJS and inside of AWS Lambda I am trying to make a POST request that calls an external API with a JSON object, creates a document with the response and then reads the contents of the file.
Coming from a Ruby background, I'm thinking the problem stems from my unfamiliarity with asynchronous programming, but I've tried using callbacks and readfileSync just to debug with no luck.
Any help would be appreciated.
var querystring = require('querystring');
var https = require('https');
var fs = require('fs');
exports.handler = function(event, context) {
console.log('Received event:', JSON.stringify(event, null, 2));
var operation = event.operation;
delete event.operation;
var accessKey = event.accessKey;
delete event.accessKey;
var templateName = event.templateName;
delete event.templateName;
var outputName = event.outputName;
delete event.outputName;
var req = {
"accessKey": accessKey,
"templateName": templateName,
"outputName": outputName,
"data": event.data
};
function doPost(data, callback) {
// Build the post string from an object
var post_data = JSON.stringify(data);
// An object of options to indicate where to post to
var post_options = {
host: 'hostname.com',
port: '443',
path: '/path/to/api',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
}
};
// Set up the request
var file = fs.createWriteStream(outputName);
var post_req = https.request(post_options, function(res) {
res.setEncoding('utf8');
res.pipe(file);
res.on('response', function(response) {
console.log(response);
});
res.on('error', function(e) {
context.fail('error:' + e.message);
})
res.on('end', function() {
context.succeed('success, end request listener');
});
});
// post the data
post_req.write(post_data);
post_req.end();
callback();
}
function printFileContents() {
fs.readFileSync(outputName, 'utf8', function (err, data) {
console.log('file contents:' + data);
});
}
switch (operation) {
case 'create':
// Make sure there's data before we post it
if(req) {
doPost(req, printFileContents);
printFileContents();
}
break;
...
}
};
In general, I'd recommend starting like this:
var querystring = require('querystring');
var https = require('https');
var fs = require('fs');
exports.handler = function(event, context) {
console.info('Received event', event);
var data = {
"accessKey": accessKey,
"templateName": templateName,
"outputName": outputName,
"data": event.data
};
// Build the post string from an object
var post_data = JSON.stringify(data);
// An object of options to indicate where to post to
var post_options = {
host: 'hostname.com',
port: '443',
path: '/path/to/api',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
}
};
var post_request = https.request(post_options, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
context.done(body);
});
res.on('error', function(e) {
context.fail('error:' + e.message);
});
});
// post the data
post_request.write(post_data);
post_request.end();
};
You can see I simplified your code quite a bit. I'd recommend avoiding the file system since that would slow down your program. I'm also not sure about what is the real goal of your function so I just return the HTTP response.