AWS Lambda Node.js HTTP GET Request never executed - javascript

I have the following intent. When intent is entered I want to perform a GET request to an external API. The intent is entered, however my http.get requested is not. If you look below I added a log statement within the request and it is never executed. Any ideas what the problem may be?
'BlogEntrySlugIntent': function () {
var url = 'http://jsonplaceholder.typicode.com/posts/1';
http.get( url, function( response ) {
console.log('In get request');
response.on( 'data', function( data ) {
var text = 'Data returned is: ' + data;
this.emit(':tell', 'hellloooo');
});
});
},

Related

Angular making pseudo-synchronous HTTP requests

I want to construct a mechanism that would access a database via POST requests. So far, I do received the desired data, but am have issues with the timing. Here are three pieces of code that I'm using (simplified to keep the focus of the question).
First, a factory handling the HTTP request vis-à-vis a servlet:
var My_Web = angular.module('My_Web');
My_Web.factory('DB_Services', function($http , $q) {
var l_Result ;
var DB_Services = function(p_Query) {
var deferred = $q.defer();
var url = "http://localhost:8080/demo/servlets/servlet/Test_ui?";
var params = "data=" + p_Query ;
var Sending = url + params ;
$http.post(Sending).
success(function(data, status, headers, config) {
deferred.resolve(data);
}).
error(function(data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
return DB_Services;
});
Second, a general purpose function handling the promise (or so I meant) exposed to all the controllers that would need to extract data from the remote DB:
$rootScope.Get_Data_from_DB = function(p_Query) {
DB_Services(p_Query).then(function(d) {
console.log("In Get_Data_from_DB; Received data is: " + JSON.stringify(d));
$scope.data = d;
});
};
Third, one example within one of the controllers:
$scope.Search_Lookups = function () {
console.log ("search for lookup data...") ;
var l_Lookup_Type = document.getElementById("THISONE").value ;
var l_Send_Request_Data = '{"Requestor_ID":"4321" , "Request_Details" : { "Data_type" : "' + l_Lookup_Type + '" } }' ;
console.log("Sending Request: " + l_Send_Request_Data) ;
l_Data = $rootScope.Get_Data_from_DB(p_Query) ;
console.log ("Received response: " + l_Data) ;
Deploy_data(l_Data) ;
}
The function Deploy_data(l_Data) is responsible of dismembering the received data and put the relevant pieces on screen.
What happens is that I get on the console the string Received response: undefined and immediately after the result of the retrieval as In Get_Data_from_DB; Received data is: (here I get the data).
The Received response: undefined is printed from the invoking function (third piece of code), whereas the output with the actual data is received and printed from within the second piece of code above. This means that the invocation to Deploy_data would not receive the extracted data.
Once again, the same mechanism (i.e. the factory $rootScope.Get_Data_from_DB) would be vastly used by many controllers.
I thought of using $scope.$watch but I'm not sure because the same user might be triggering several queries at the same time (e.g. request a report that might take few seconds to arrive and, in the meantime, ask for something else).
I think I found a solution (at least it appears to be ok for the time being). The global function Get_Data_from_DB accepts a second parameter which is a callback of the invoking controller.
The invoking controller creates a private instance of the Get_Data_from_DB function and triggers a request providing the callback function.
I'll need to test this with parallel queries, but that is still a long way to go...

Node Express pass variable from client to server

I am trying to return value from an input box to a variable in route, by taking this source as a reference but am stuck, in the example author is searching a keyword, constructing a url using this keyword, and returning a body response.
My use case is a little different I need user to provide a url as a string in search box, which I would then pass to my request function to spit response body
Current app.js (server-side)
app.get('/searching', function(req, res){
// input value from search
var url = req.query.search;
console.log(url); // prints value
request({ uri: url}, function (error, response, body) {
if (!error) {
content = body;
console.log(content);
} else {
console.log('Oops! Error when contacting slack.com');
}
});
res.send(content);
});
main.js (client-side)
$(function(){
$('#submit').on( 'click', function () {
var sSearch = $('#search').val();
var parameters = { search: sSearch };
$.get( '/searching',parameters, function(data) {
$('#results').html(data);
});
});
});
I realize /searching in both above files must be replaced because currently its trying to 'search' the user entered url value as a query string, so if I enter "https://google.com" in the text box the application tries to search:
http://localhost:3000/searching?search=https%3A%2F%2Fgoogle.com
instead I need it to pass this url as is to the request function so that I can print the body response, which in this case would be the page's source code. But am not sure how should I proceed
index.jade (template)
extends layout
block content
input#search(type="search", placeholder="Enter Keyword")
button#submit(type='submit',class='btn btn-success') Search
h2#results
script(src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js")
script(src="/javascripts/main.js")
How should I format so that I can pass the variable from client to server and then send it back to client after processing? Any help is appreciated.
In the app.js you are making a async http call, but the response is sent before the http callback is invoked. Just move the res.send(content); inside the call back
app.get('/searching', function(req, res){
// input value from search
var url = req.query.search;
console.log(url); // prints value
request({ uri: url}, function (error, response, body) {
if (!error) {
content = body;
console.log(content);
} else {
console.log('Oops! Error when contacting slack.com');
}
res.send(content);
});
});
i see ajax request in your client code , so in your server code, try to response something like this :
res.status(200).json(content)
in your client code ,check if the content is there (console.log(data) before $().html(data)... )
PD : request is async , so you have to response inside request callback.

Fetch data on different server with backbone.js

I can't see what the problem with this is.
I'm trying to fetch data on a different server, the url within the collection is correct but returns a 404 error. When trying to fetch the data the error function is triggered and no data is returned. The php script that returns the data works and gives me the output as expected. Can anyone see what's wrong with my code?
Thanks in advance :)
// function within view to fetch data
fetchData: function()
{
console.log('fetchData')
// Assign scope.
var $this = this;
// Set the colletion.
this.collection = new BookmarkCollection();
console.log(this.collection)
// Call server to get data.
this.collection.fetch(
{
cache: false,
success: function(collection, response)
{
console.log(collection)
// If there are no errors.
if (!collection.errors)
{
// Set JSON of collection to global variable.
app.userBookmarks = collection.toJSON();
// $this.loaded=true;
// Call function to render view.
$this.render();
}
// END if.
},
error: function(collection, response)
{
console.log('fetchData error')
console.log(collection)
console.log(response)
}
});
},
// end of function
Model and collection:
BookmarkModel = Backbone.Model.extend(
{
idAttribute: 'lineNavRef'
});
BookmarkCollection = Backbone.Collection.extend(
{
model: BookmarkModel,
//urlRoot: 'data/getBookmarks.php',
urlRoot: 'http://' + app.Domain + ':' + app.serverPort + '/data/getBookmarks.php?fromCrm=true',
url: function()
{
console.log(this.urlRoot)
return this.urlRoot;
},
parse: function (data, xhr)
{
console.log(data)
// Default error status.
this.errors = false;
if (data.responseCode < 1 || data.errorCode < 1)
{
this.errors = true;
}
return data;
}
});
You can make the requests using JSONP (read about here: http://en.wikipedia.org/wiki/JSONP).
To achive it using Backbone, simply do this:
var collection = new MyCollection();
collection.fetch({ dataType: 'jsonp' });
You backend must ready to do this. The server will receive a callback name generated by jQuery, passed on the query string. So the server must respond:
name_of_callback_fuction_generated({ YOUR DATA HERE });
Hope I've helped.
This is a cross domain request - no can do. Will need to use a local script and use curl to access the one on the other domain.

making ajax request in meteor helpers

How can i wait until the ajax request finishes when returning data to a meteor helpers method.
For example,
Template.item.helpers({
itemName:function () {
var user = Meteor.user();
$.when(reallyLongAjaxRequest()).done(function (a1) {
//tried using jquery when
return "Item Name should have this because it waited";
});
return " Doesnt wait at all";
}
});
I have a reallyLongAjaxRequest() running and i would like it to finish before continuing on with my itemName helper. The log statement to console always shows undefined but that's because the ajax request hasn't finished. I tried using the jquery when with no luck. Any ideas
Edit:
I should mention that i am inside the helper function for a reason. I need the item 'id' being rendered so that i can run the ajax request with that paramater. Using reactive sessions would be perfect but i don't know of a way to get currently rendering items outside of the helpers method definition?
An unnamed collection is one where null is passed for the name. It is an in-memory data structure, not saved to the database. (http://docs.meteor.com/#meteor_collection)
OK, given a Meteor collection called "items" and wanting to do an ajax request for each item based on the item _id, and then being able to reference the ajax result in a template, this is what I'd do:
(roughly)
var Items = new Meteor.Collection('items');
var Results = new Meteor.Collection(null);
Items.find().observeChanges({
added: function (id) {
$.get(url, {id: id}, function (data) {
if (Results.findOne(id))
Results.update(id, {$set: {result: data}});
else
Results.insert({_id: id, result: data});
});
}
});
Template.item.itemName = function (id) {
var doc = Results.findOne(id);
if (doc)
return doc.result;
else
return "";
};
inside your html you'll need to pass in the id to the helper:
{{itemName _id}}
Is there no way to just timeout for a few seconds when defining the helper so that my ajax request finishes without immediately returning.
No, with reactive programming things happen immediately, but you update when you have new stuff.
Make your ajax request separately, and when it completes, have it store the result in a Session variable. Then have your template helper return the value of the Session variable. Roughly...
$.get(url, function (data) {
Session.set('result', data);
});
Template.item.itemName = function () {
return Session.get('result');
};
Session is a reactive data source, so your template will automatically updated when the result of the ajax call comes in. (Naturally you can choose to call the Session variable anything you like, I just used "result" as an example).
This works and tested in MeteorJS > 1.3.x
Add the http package from the console meteor add http
Example POST call with data elements being sent to server and with custom headers.
HTTP.call('POST', tokenUri, {
data: {
"type": 'authorization_code',
//"client_id": clientId,
"code": code,
"redirect_uri" : redirectUri,
},
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : "true",
"Access-Control-Allow-Methods" : "GET,HEAD,OPTIONS,POST,PUT",
"Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers",
}
},function(error, response) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});

Posting to Twitter through OAuthSimple.js

I've been stuck on this one for a while. I'm trying to use OAuthSimple.js to interact with Twitter in a Chrome extension I've written.
The signing process seems to work fine for requests to retrieve a user's statuses, but I can't seem to construct a request that will successfully authenticate when I try to retweet, reply, or mark a tweet as favorite.
I'm following the guides here. I have also tried numerous ways of structuring the request, and comparing the request contents against the output of the OAuth tool provided by Twitter ( which seems to check out ), but I'm still getting 401 errors and generic "We couldn't authenticate you" responses.
Here's how I'm trying to form the request:
var sendTwitterRequest = function(url, params, method, callback) {
var request = null;
if ( localStorage.twitterAuthToken ) {
OAuthSimple().reset();
request = OAuthSimple(TwitterConsumerKey,TwitterConsumerSecret).sign({
action:method,
method:"HMAC-SHA1",
dataType:"JSON",
path:url,
parameters:params,
signatures:{
oauth_version:'1.0',
oauth_token:localStorage.twitterAuthToken,
oauth_secret:localStorage.twitterAuthVerifier
}
});
console.log(request);
$j.ajax({
url:request.signed_url,
type:method,
data:request.parameters,
success:callback
});
}
};
Then, making calls into this method like this:
// this works, I get the data and can do stuff with it
sendTwitterRequest('http://api.twitter.com/1/statuses/user_timeline.json?user_id=',null,'GET',someMethod());
// this fails and throws a 401 error every time
sendTwitterRequest("https://api.twitter.com/1/statuses/retweet/"+tweetKey+".json",null,'POST',someOtherMethod());
Am I missing something? Thanks in advance!
It turns out the requests I am creating are fine, I just needed a final one to exchange request tokens for OAuth tokens. I thought this step was covered when the user was prompted for input, but turns out I was wrong.
I also ended up switching from OAuthSimple.js to just OAuth.js, on account of the fact that I could only get OAuth.js to process both the token requests and the timeline requests.
Some of this is pretty specific to what my application is doing, so you will probably need to modify it.
The new sendTwitterRequest method:
var sendTwitterRequest = function(options){
var accessor={
consumerSecret:TwitterConsumerSecret
};
var message={
action:options.url,
method:options.method||"GET",
parameters:[
["oauth_consumer_key",TwitterConsumerKey],
["oauth_signature_method","HMAC-SHA1"],
["oauth_version","1.0"]
]
};
if(options.token){
message.parameters.push(["oauth_token",options.token])
}
if(options.tokenSecret){
accessor.tokenSecret=options.tokenSecret
}
for(var a in options.parameters) {
message.parameters.push(options.parameters[a])
}
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message,accessor);
try {
$j.ajax({
url:message.action,
async:options.async||true,
type:message.method||'GET',
data:OAuth.getParameterMap(message.parameters),
dataType:options.format||'JSON',
success:function(data) {
if (options.success) {options.success(data);}
}
});
} catch ( e ) {
}
};
And the methods that depend on it:
// asks Twitter for an oauth request token. User authorizes and the request token is provided
requestTwitterToken = function() {
// this is semi-specific to what my extension is doing, your callback string may need
// to be slightly different.
var callbackString = window.top.location + "?t=" + Date.now();
var params = [
[ 'oauth_callback', callbackString ]
];
sendTwitterRequest({
url: "https://api.twitter.com/oauth/request_token",
method: 'POST',
parameters: params,
format: 'TEXT',
success: function(data) {
var returnedParams = getCallbackParams(data);
if ( returnedParams.oauth_token ) {
chrome.tabs.create({
url:"https://api.twitter.com/oauth/authorize?oauth_token=" + returnedParams.oauth_token
});
}
},error:function( e ) {
console.log( 'error' );
console.log( e );
}
});
};
// exchanges the Twitter request token for an actual access token.
signIntoTwitter = function(token, secret, callback) {
var auth_url = "https://api.twitter.com/oauth/access_token";
var authCallback = function(data) {
var tokens = getCallbackParams(data);
localStorage.twitterAuthToken = tokens.oauth_token || null;
localStorage.twitterAuthTokenSecret = tokens.oauth_token_secret || null;
callback();
};
try {
sendTwitterRequest({url:auth_url, method:'POST', async:true, format:'TEXT', token:token, tokenSecret:secret, success:authCallback});
} catch ( e ) {
console.log(e);
}
};
With this, the steps are as follows:
ask Twitter for a token ( requestTwitterToken() ) and provide a callback
in the callback, check to see if a token is provided. If so, it's an initial token
pass the token back to Twitter and open the Twitter auth page, which allows the user to grant access
in the callback to this call, see if an access token was provided
exchange the request token for an access token ( signIntoTwitter() )
After that, I simply use the sendTwitterRequest() method to hit Twitter's API to fetch the timeline and post Tweets.

Categories