Accessing Cloudant database with jQuery - javascript

I'm trying to connect to my CouchDB on Cloudant using jQuery and jQuery.couch.sj
However, I can't even get the most basic info about my database. For example the following code prints nothing to the console.
Code
<script>
$.couch.urlPrefix ="https://acharya.cloudant.com";
$.couch.info({
success: function(data) {
console.log(data);
}
});
</script>
I've looked at the online documentation but to no avail.
If I type
var db= $.couch.db("toxtweet");
console.debug(db);
to see something about one of my CouchDB's, I get:
Object { name="toxtweet",uri="https://acharya.cloudant.com/toxtweet/", compact=function(),
more...}
And that is the correct URI. So, how would I, for example, get the number of documents in the "toxtweet" database? Trying the example doesn't work.
Update
If I view the page in Chrome instead of Firefox I see the following error.
XMLHttpRequest cannot load https://acharya.cloudant.com/. Origin http://tox.sinaiem.org is not
allowed by Access-Control-Allow-Origin.
I thought that Cloudant was a CouchApp that bypassed the same-origin policy.

I haven't used jquery to access Cloudant, but I would expect you to have to log in somewhere first unless you have somehow made your database public.
Have you checked in Chrome or Firefox what https requests and responses jquery.couch is sending and receiving?
To get the number of documents, you would typically have a view with a reduce method like this:
// map
function(doc) {
emit(doc.id, 1);
}
// reduce
function(keys, values, rereduce) {
return sum(values);
}
see here for more info What is the CouchDB equivalent of the SQL COUNT(*) aggregate function?
I would recommend you use Futon when trying out examples before doing an equivalent request in jquery.couch
Update
Have you tried JSONP to get around cross domain issue?
see here: http://support.cloudant.com/customer/portal/articles/359321-how-do-i-read-and-write-to-my-cloudant-database-from-the-browser-

CouchApp's/Cloudant don't bypass same origin policy. If you have a CouchApp on Cloudant you can access it under your domain (e.g. https://acharya.cloudant.com/DB_NAME/_design/DESIGN/index.html), if you want that on another domain you'll need a reverse proxy as AndyD suggests.
The CouchDB wiki has two nice run throughs for using HTTPD or Nginx as a reverse proxy, both should apply when running against a database hosted in Cloudant.
HTH
Simon

Related

How to capture query string parameters from network tab programmatically

I am trying to capture query string parameters for analytics purpose using javascript. I did some searching and found that BMP can be used to do it but i am unable to find ample examples to implement. Could anyone point me in the right direction.
EDIT 1:
I used below code using browsermob-proxy to get har file but i get ERROR: browsermob-proxy returned error when i run it . I use selenium with it.
getHarFile() {
const proxy = browsermb.Proxy;
const pr = new proxy({host:"0.0.0.0",port:4444});
pr.doHAR("http://www.cnn.com/", (err,data) => {
if (err) {
logger.debug('ERROR: ' + err);
} else {
fs.writeFileSync('ua.com.har', data, 'utf8');
logger.debug("#HAR CREATED#");
}
})
}
So since I´m not quite sure of your scope I will throw you some ideas:
1. Fixing browsermob-proxy
You should change the host and proxy of the browsermob-proxy. Change the host to 127.0.0.1 and the port with any random number (4444 its ok). Then, make sure your browser run in that host and proxy by changing the browser settings.
2. Using plain javascript
2.1 Get current page query string
You can get the query string using location.search. If you are using some BDD framework with selenium, it is possible to execute javascript code and retrieve the result. You should always add a return to your code in order to recieve the response in your BDD test.
2.2 Using Performance API
You can access to all the network information within performance api. If you need to get the current page url you can use the following code:
performance.getEntriesByType("navigation")
This will return all the current navigation events and information.
If you want to get some information of the calls that the page made you can access it using:
performance.getEntriesByType("resource")
This will return all the calls made by your site. You have to loop over it searching the resource you want to find.
In all the ways, there is no way to get the value and key of query string as in the network tab. You have to separate it manually with a function, you can use the code provided here to get the value of a key.
My suggestion is to create your personal extension for Google Chrome, and developing an extension you can access few more apis that are not available by default in the console.
For example you will have this object in order to inspect the network tab:
chrome.devtools.network
Here two links you may find useful:
https://developer.chrome.com/extensions/devtools
https://developer.chrome.com/extensions/devtools_network
I hope it helps
I was finally able to do it using the s object available on chrome console. The url with encoded query string was available as s.rb object in chrome console. I just decoded it and extracted the query string parameters.

sharePoint online count unread message from office365

As part of a project whose aim is to notably improve the visual side of a SharePoint Online site, I'm a bit stuck. On the home page in the left banner, users want to see the number of unread messages they have in Office365.
I created an area in the master page to put the result in. I thought the Rest API used to do this :
$.ajax ({
type: "GET",
url: " https://outlook.office365.com/ews/odata/Me/Folders/Inbox",
dataType : "json",
success : function (resp) {
// count unread messages
},
error : function (e) {
alert (' Error121212 :' + JSON.stringify (e));
}
})
Unfortunately I get an error like cross domain. I tried with JSONP but it does not work either (uncaught syntax error unexpected token).
Can you please tell me if this is a good practice? I feel that it anyways I must find a technic for authentication. (In the case of JSONP I have a popup that asks me authentication and then problem occurs on callback apparently)...
I want to avoid developing a type requiring a typical deployment Wsp...
Thank you in advance for your help.
Your URL for the ajax request seems incorrect. The URL for getting the inbox messages via the API is: https://outlook.office365.com/api/v1.0/me/folders/inbox/messages
Once you get the response, you can count the number of objects with the IsRead property set to false using a simple for loop and display that count.
The issue here is related to CORS and how browsers refuse to handle cross-domain requests. To get around this, typically you would either
Change the response header on the remote server - not an option here
Use some sort of proxy to handle the requests - here's where SharePoint apps come in.
I know you stipulated that you want to avoid using a WSP style deployment but there simply isn't a way around it, you have to use the SharePoint App Model
This article goes a long way to answer your question, but for completion the basic steps are as follows
Create a SharePoint hosted app in Visual Studio
In the App Manifest, you need to define the trust relationship with the remote host (in this case the host of outlook.office365.com) using the AppManifest section
Use SP.RequestExecutor.executor to make the request on your behalf

What is the best/proper configuration? (javascript SOAP)

I need to retrieve data from a web service (via SOAP) during a nightly maintenance process on a LAMP server. This data then gets applied to a database. My research has returned many options and I think I have lost sight of the forest for the trees; partially because of the mix of client and server terms and perspectives of the articles I have read.
Initially I installed node.js and node-soap. I wrote a simple script to test functionality:
var soap = require('/usr/local/lib/node_modules/npm/node_modules/soap');
var url = "https://api.authorize.net/soap/v1/Service.asmx?WSDL";
soap.createClient(url, function(err, client)
{
if(typeof client == 'undefined')
{
console.log(err);
return;
}
console.log('created');
});
This uses a demo SOAP source and it works just fine. But when I use the actual URL I get a 5023 error:
[Error: Invalid WSDL URL: https://*****.*****.com:999/SeniorSystemsWS/DataExportService.asmx?WSDL
Code: 503
Response Body: <html><body><b>Http/1.1 Service Unavailable</b></body> </html>]
Accessing this URL from a browser returns a proper WSDL definition. I am told by the provider that the 503 is due to a same-origin policy violation. Next, I researched adding CORS to node.js. This triggered my stepping back and asking the question: Am I in the right forest? I'm not sure. So, I am looking for a command-line, SOAP capable, CORS app (or equivalent) configuration. I am a web developer primarily using PHP and Javascript, so Javascript is where I turned first, but that is not a requirement. Ideas? Or, is there a solution to the current script error (the best I think I have found is using jQuery in node.js which includes CORS)
Most likely, this error belongs to your website server.
Please go through this link, it might be helpful.
http://pcsupport.about.com/od/findbyerrormessage/a/503error.htm
Also you can open your wsdl in web browser, search for soap:address location tag under services. And figure out correct url, you are trying to invoke from your script. Directly access this url in browser and see what are you getting.
I think I have a better approach to the task. I found over the weekend that PHP has a full SOAP client. I wrote the same basic login script in PHP and it runs just fine. I get a valid authentication code in the response to loginExt (which is required in further requests), so it looks like things are working. I will comment here after verifying that I can actually use the web service.

Unable to authorize to couchdb using $.couch.login

in my CouchDB setup i have the following configuration
CORS in configuration is enabled (it worked before i locked down the database)
a basic admin with name admin and password admin exists
localsite is http://localhost/mysite and couchdb is located in http://localhost:5984/
i have avoided to use any server-side scripting and just serve the static files, the rest is handled in client-side, so if it's possible, do not write your entire answer based on server-side PHP or node.js.
Tried to login with $.couch.login it returns
{"ok":true,"name":null,"roles":["_admin","admin"]}
the i try to request $.couch.session and instead of a populated json it justs returns
{"ok":true,"userCtx":{"name":null,"roles":[]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"]}}
when i tried with a REST tool , the result was
{"ok":true,"userCtx":{"name":"admin","roles":["_admin","admin"]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"],"authenticated":"cookie"}}
when worked with the REST tool, it allowed me to continue , with adding documents, deleting , and so on.
What exactly am i missing here?
Well the following code allowed for cookie in headers.
$.ajaxSetup({
crossDomain:true
,xhrFields:{ withCredentials:true}});

Google OAuth WildCard Domains

I am using the google auth but keep getting an origin mismatch. The project I am working has sub domains that are generated by the user. So for example there can be:
john.example.com
henry.example.com
larry.example.com
In my app settings I have one of my origins being http://*.example.com but I get an origin mismatch. Is there a way to solve this? Btw my code looks like this:
gapi.auth.authorize({
client_id : 'xxxxx.apps.googleusercontent.com',
scope : ['https://www.googleapis.com/auth/plus.me',
state: 'http://henry.example.com',
'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'],
immediate : false
}, function(result) {
if (result != null) {
gapi.client.load('oath2', 'v2', function() {
console.log(gapi.client);
gapi.client.oauth2.userinfo.get().execute(function(resp) {
console.log(resp);
});
});
}
});
Hooray for useful yet unnecessary workarounds (thanks for complicating yourself into a corner Google)....
I was using Google Drive using the javascript api to open up the file picker, retrieve the file info/url and then download it using curl to my server. Once I finally realized that all my wildcard domains would have to be registered, I about had a stroke.
What I do now is the following (this is my use case, cater it to yours as you need to)
On the page that you are on, create an onclick event to open up a new window in a specific domain (https://googledrive.example.com/oauth/index.php?unique_token={some unique token}).
On the new popup I did all my google drive authentication, had a button to click which opened the file picker, then retrieved at least the metadata that I needed from the file. Then I stored the token (primary key), access_token, downloadurl and filename in my database (MySQL).
Back on step one's page, I created a setTimeout() loop that would run an ajax call every second with that same unique_token to check when it had been entered in the database. Once it finds it, I kill the loop and then retrieve the contents and do with them as I will (in this case I uploaded them through a separate upload script that uses curl to fetch the file).
This is obviously not the best method for handling this, but it's better than entering each and every subdomain into googles cloud console. I bet you can probably do this with googles server side oauth libraries they use, but my use case was a little complicated and I was cranky cause I was frustrated at the past 4 days I've spent on a silly little integration with google.
Wildcard origins are not supported, same for redirect URIs.
The fact that you can register a wildcard origin is a bug.
You can use the state parameter, but be very careful with that, make sure you don't create an open redirector (an endpoint that can redirect to any arbitrary URL).

Categories

Resources