Node.js socket hang up error when connecting to twitter api - javascript

I'm getting socket hang up error , when connecting to twitter streaming api with basic authentication using https. I think the error is occurring when doing the authentication.
var https = require("https");
var options = {
host: 'stream.twitter.com',
path: '/1.1/statuses/filter.json?track=bieber',
method: 'GET',
headers: {
"Authorization": "Basic " + new Buffer('UserName' + ":" + 'Password').toString("base64")
}
}; //end of options
var request = https.request(options, function(response){
var body = '';
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.on("data", function(chunk){
var tweet = JSON.parse(chunk);
console.log("Tweet " + tweet.text);
}); // end of data
response.on("end", function(){
console.log("Disconnected!!");
}); // end of end
response.on("error", function(){
console.log("error occured");
}); // end of error
}); // end of request
request.on("error",function(error){
console.log("Error: " + error.message);
}); // end of error
When i try to access this url it works fine.
https://username:password#stream.twitter.com/1.1/statuses/filter.json?track=twitter

Change https.request(options, function(response){ } to https.get(options, function(response){ } Thanks to Darrenlooby on nodejs IRC for pointing it out.

You can use https.request, but make sure you add:
request.end();
where request is the object returned from https.request
See http://nodejs.org/api/https.html#https_https_request_options_callback for an example.
I had the same issue and this fixes it :)

Related

Ldapjs search does not appear to end

I'm new to ldapjs and ldap in general. I have the following code currently:
var search = client.search(base, opts, function(err, res) {
assert.ifError(err);
res.on('searchEntry', function(entry) {
console.log('entry: ' + JSON.stringify(entry.object));
});
res.on('searchReference', function(referral) {
console.log('referral: ' + referral.uris.join());
});
res.on('error', function(err) {
console.error('error: ' + err.message);
});
res.on('end', function(result) {
console.log('status: ' + result.status);
});
});
My search occurs correctly and finds everything needed. My issue is that it does successfully get to res.on('end') and prints out the status code (0) but the script I'm running never "officially" ends and thus causes me to have to perform a keyboard interrupt.
Additionally I tried using res.end() but was informed this was not a function. Is there something I am missing entirely? Thanks!
I think it is more nodejs question rather than ldapjs.
You can add exit your program on the 'end' event.
See:
How to exit in Node.js
Try doing this for your res.on('end'...)
res.on('end', (result => {
console.log('status: ' + result.status);
client.destroy();
});

No 'Access-Control-Allow-Origin' header is present on the requested resource. (google contacts api)

I am trying to get photo of google contact. from api guide found this:
https://www.google.com/m8/feeds/photos/media/{userEmail}/{contactId}
my code:
`$.get("https://www.google.com/m8/feeds/photos/media/default/54b8abe0f52ad02?access_token=" + authorizationResult.access_token + "&v=3.0",
function(response){
//process the response here
console.log(response);
}
);`
it gives me this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
but this seems to be working fine
`$.get("https://www.google.com/m8/feeds/contacts/default/full?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
//process the response here
console.log(response);
}
);`
Edit:
full js script:
`
<script type="text/javascript">
var clientId = 'my client id';
var apiKey = 'api key';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
$(document).on("click",".googleContactsButton", function(){
gapi.client.setApiKey(apiKey);
window.setTimeout(authorize);
});
function authorize() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
}
function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
$.get("https://www.google.com/m8/feeds/photos/media/default/54b8abe0f52ad02?access_token=" + authorizationResult.access_token + "&v=3.0",
function(response){
//process the response here
console.log(response);
}
);
}
}
</script>
`
I got the picture by doing this: (prefix image url with proxy url)
` function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
console.log(authorizationResult);
var accessToken = authorizationResult.access_token;
$.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + accessToken + "&max-results=500&v=3.0",
function(response){
//process the response here
console.log(response);
let photoUrl = response.feed.entry[2].link[0].href + "&access_token=" + accessToken;
let proxy = 'https://cors.now.sh/';
let finalPhotoUrl = proxy + photoUrl;
document.getElementById('photo').src = finalPhotoUrl;
}
);
}
}`

node.js download images to server from list of http requests

I'm very new at node so bear with me. I'm trying to download a series of images from an external server. So far I have been able to get it working on a limited basis. When I run the below code, only about half of the images make it though to the web page. I know that I'm not doing this correctly, and am looking for some guidance. Here is the code that I have so far
var request = require("request"),
fs = require("fs"),
views = ['sitename1', 'sitename2', 'sitename3'...]
for (var view in views) {
request({
url: 'http://' + SERVERURL + '/api/2.2/sites/' + siteID + '/workbooks/' + views[view]['workbookID'] + '/views/' + views[view]['id'] + '/previewimage',
headers: {
'Content-Type': 'image/png',
'X-Tableau-Auth': authToken
}
, encoding: 'binary'}).pipe(
fs.createWriteStream('./public/images/thumbnails/' + SITE + '/views/' + views[view]['url'] + '.png'
))
};
I want to point out that this does get some of the images saved correctly. I believe what I'm missing is a callback to make sure that the file has been successfully saved before moving on to the next item in the list. I have no idea how to implement that.
Another quick note (not important) is that I'm trying to download images from a Tableau Server using the REST api.
The face you're getting about half the images makes me wonder if you are using Tableau Online? If so, you need to ensure you're using the URI per the docs (http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_concepts_fundamentals.htm#tableau-online-uris).
Just figured it out using the async module
async.eachSeries(views, (function(view, callback) {
var thumbPath = 'public/images/thumbnails/' + req.session.SITE + '/views/' + req.session.views[view]['url'] + '.png'
request({
url: 'http://' + SERVERURL + '/api/2.2/sites/' + req.session.siteID
+ '/workbooks/' + req.session.views[view]['workbookID'] + '/views/' + req.session.views[view]['id'] + '/previewimage',
headers: {
'Content-Type': 'image/png',
'X-Tableau-Auth': req.session.authToken
}
}).pipe(
upload(thumbPath));
callback()
}),
function(err){
if(err){
console.log("a thumb failed to download")
} else {
console.log("all thumbs downloaded")
}
}
)

Save files from remote server into mobile device

I am working on Cordova 2015 Apache cordova app . I want to recieve files from remote server such as https://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf and save it into my device.
$("#SaveFile").click(function () {
var _fileTransfer = new FileTransfer();
var filePath = cordova.file.dataDirectory + "Download/tost.pdf";
var uri = encodeURI("https://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf");
_fileTransfer .download(
uri,
filePath,
function (entry) {
alert("download complete: " + entry.fullPath);
},
function (error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
});
When I 'v debugged it always go to error function
1st error describe the source:
2nd error describe the target:
. and i didn't get any thing in download folder .
here is a list of mobile paths from the w3c standard: http://wiki.phonegap.com/w/page/35605874/Planning%3A%20File%20API
and here is how you use it with phonegap: http://docs.phonegap.com/en/1.4.1/phonegap_file_file.md.html#LocalFileSystem
so you have to request the file system onSuccess you can use the path
here a full example: Writing and reading file in phonegap

Facebook post custom action to timeline

I have created a custom action that I want to allow users to post to their timeline with e.g. {User} read {Article}. I can get this to work fine when I do a post using the sample URL like this :
FB.api('/me/fbsite:actionname' +
'?object=http://samples.ogp.me/356694057772404&access_token=abc','post'
But when I replace the sample URL with my own URL I get the error 'The session was invalidated explicitly using an API call'. Can anybody please advise?
EDIT : Changed my Javascript to this, but I now get 'Invalid OAuth Access Token' :
<script type="text/javascript">
function redeem() {
FB.api('/me/fbsite:actionname' +
'?object=http://samples.ogp.me/356694057772404&access_token=\' + <%=UserManager.Current.FB.accessToken %> + \'', 'post',
function (response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: " + response.error.type + "\n\nMessage: " + response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
That might be because you are using the same access token in same session. So try logging out and log back in, get a new FB access token, and try the query using the new access token you got, that should work as expected.

Categories

Resources