Add data to couchdb with jsonp response - couchdb

Is there a way add data to a couchdb that runs on another domain and get back an response whether the operation was successfully or not? I know couchdb supports jsonp callback but can I add data with this approach?

No, you cannot currently do this. CouchDB's REST API requires a POST or PUT request in order to insert data, but JSONP only supports GET requests. So you can retrieve data from CouchDB across domains, but updates/inserts/deletes won't work.

You can use client-side javascript to make a form to do the POST, direct the output to an iframe, and use cross-window iframe messaging to get the result.
Of course, someone has already made a nice javascript library to do this. Get the code here:
https://github.com/benvinegar/couchdb-xd
Follow the instructions to push it as an additional database on your couchdb server. Then, on any site, include one not in the 'your-couch-server' domain, you can do the following (just try it in the javascript console):
jQuery.getScript(
"http://YOUR-COUCH-SERVER/couchdb-xd/_design/couchdb-xd/couchdb.js",
function() {
Couch.init(
function() {
var s = new Couch.Server('http://YOUR-COUCH-SERVER/');
var d = new Couch.Database(s,'YOURDB');
d.put(
"stackoverflow-test 1",
{ foo: 111, bar: 222 },
function(resp) {
console.log(resp);
}
);
}
)
}
);
The above presumes you have jquery is already loaded on the page. If not, you'll need to add it however you're currently interacting with the other page.
The library only works on modern browsers with window.postMessage() support, though a small patch may eventually allow older browsers to use it via src/hash communication.

Related

Can i use AJAX request to update the whole page like reqular http requests?

If i can update the whole page with AJAX when and why should i use regular http methods?
Can AJAX requests replace normal http methods?
i am using nodeJS expressJS
Yes, you can update the whole page using AJAX. Send request from user end and get back an JSON array from server containing all the information you want.
If you want to load data from .txt file or .html, then
$.ajax({ url: 'http://website/some'
, type: 'GET'
, dataType: 'html'
})
.done(function(data) {
$('#container').html(data);
})
.fail(function() {
console.log("Something went wrong!");
});
Just wondering why you are looking at AJAX when you need a complete reload.
Yes, definitely you can. But You will not ask this question once you know the use of AJAX.
For example, you will never ever update the whole page if you are using AJAX. For example, at least Navigation will remain the same and the body part will change. This is the use of AJAX and many web applications load like this. They keep navigation the same and then update rest of the web page.
You will have this kind of application where you will update the body of the page. You can use REST API to fetch the data in the form of JSON and then load this data using styling and Javascript framework like Angular, React, Backbone, etc.

Sending POST from node.js - how does a website identify me?

there is a website that works with virtual items for an online game. I made a chrome extension that automates some actions on that website. Since I'd like to make this run on my raspberryPi (and chromium with the extension seems to be too slow and unefficient) I am trying to move this into node.js.
The login for the website works with Steam OpenID. It allows you to select items from a list, click a few buttons, then it sends you a tradeoffer on steam.
My extension works with the website while I was logged in there. It receives their database with jQuery getJSON, loops through the array, pushes some values into an array and then sends a post request telling the website which items I want and which items I am offering.
Here is how I am sending the request from chrome:
function withdrawXHR(botId, playerItems, botItems) {
$.ajax({
url: websiteURL,
type: 'post',
data: {
"steamid": botId,
"peopleItems": playerItems,
"botItems": botItems
},
success: function (data) {
console.error('>> Done: ' + data)
console.log("")
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.error('>> Error: ' + errorThrown)
console.log("")
}
});
}
I can do everything in node so far like receiving their database, working through it, filter out the values I need, but I can't manage to send a working request. The problem is probably the login / how the website knows who I am.
I used wrapAPI (a chrome extension) to catch the request that is being sent when manually working with the website. Here is what it looks like:
So these are the things I am wondering about:
How would I send this request from node?
How does the website know who I am? They obviously know, because they are sending me an offer, but I can't see any "personal" data in that request.
Would I need to log into Steam OpenId from Node in some way? Is that possible?
What is a CF-RAY? (See the end of the captured request).
I am quite new to JS and requests in general and even "newer" to Node.js. I don't fully understand how the background of sending requests works. I would just need some tips, ideas on how to achieve my goal here.
Any help is greatly appreciated! Thank you! :)
You cannot use XMLHttpRequest for resources across domains. ( incidentally, unless you are using an extension)
I would look into grabbing express.js, and something called CORS. CORS permits cross-domain requests.
Here: http://enable-cors.org/server_expressjs.html
And here is some information on XHR requests in browser extensions: https://developer.chrome.com/extensions

Using socket.io with sails js

While there used to be very good documentation for using sockets, thanks to Irl Nathon's Sails Cast series. Things have changed in v0.11, with the sails team wrapping and burying the socket.io routines.
The sails site e.g. SailsSocket is maddeningly concise, saying what to do, but not how or where to do it, or if I need to npm or bower something. This has been particularly frustrating trying to use the sails.config.sockets talked about on the sails site. Which I cannot even find in my v0.11 directories.
First, I would like to know how and where to create my own response to a io.socket.get or .post or whatever. Right now when I do a get with something like:
`io.socket.request({
method: 'get',
url: '/sites/2',
params: {},
headers: {}
},function serverResponded(body, JWR){console.log("Body: ", JSON.stringify(body,null, 4)); console.log(' JWR: ', JWR.body)});'
I get back:
undefined
VM1149:7 "Not implemented in core yet"
VM1149:7 JWR: Not implemented in core yet
I can see the sites being called in the sails console, but nothing comes across.
I believe it is because I have defined my own routes and have my own find: function in my site controller and I manually need to push something into the server side socket. But I am confused as to how I am to call a whole page with HTTP and just the tables with socket.io in the same controller routine.
Where do I write my own low level socket.io routines that can be called from a web page?
Do I still do it in the app.js file?
Sails Cast showed it being done there, but again things have changed.
Sails "virtual requests" (what they call these socket.io-based HTTP-ish request) are generally used to retrieve or post JSON data to the server. Additionally, if a client-side script makes a virtual request, the server may add or remove the requesting socket to/from rooms.
Note that using a "virtual method" will ultimately run the same controller action, but will set req.isSocket = true.
This example is a view that renders a view for HTML-wanting requests but returns JSON data for socket-based requests:
...
// 'get /sites/:id': 'SomeController.showSite' (should be put in your `routes.js`)
showSite: function(req, res) {
// load something from the database
Site.findOne(req.param('id')).exec(function(err, site) {
// handler errors (same for HTTP or sockets)
if (err) return res.serverError();
if (!site) return res.notFound();
if (req.isSocket) return res.json(site); // render JSON response for our `site` object
else return res.view('sites/show', {site: site}); // render an HTML view
});
}
As for low-level socket.io, sails provides the global variable io (from sails.io.js), which is an instance of SailsSocket. It allows you to make HTTP-ish "virtual requests". More info here (although it seems you have already read all there is to read about SailsSocket :). You can access the underlying socket.io client with io.socket._raw.
// do this in the browser.
// sails.io.js should be included in layout.ejs by default.
io.socket.get('/site/2', console.log); // "virtual request"
// neat little trick ^^^^^^^^^^^ for testing :)
var rawIO = io.socket._raw;
rawIO.emit('some:event', "using native socket.io");
Hope this helps!

React Node API Request Design Pattern

I need to make an API request to an external API using an API Key. I know how to make this API request in React by writing a onSubmit function. But since I have an API key that I want to keep a secret I am going to write a simple Node app to house env variables.
Besides messing around in node this is my first production experience with Node and I am wondering if my thought process is correct and if not, the better way to do this.
Most of this question will be pseudo code since I haven't started with the Node portion yet.
The idea is that from within the React component it would call the Node app who in turn would call the external API.
React -> Node -> External API
So the React component would be something like so:
handleSubmit: function() {
var data = this.refs.testData.getDomNode().value;
$.ajax({
url: '/my-node-endpoint',
dataType: 'json',
type: 'POST',
data: { test: data },
success: function(data) {
// Whatever success call I want to make
}.bind(this)
})
}
And then in my Node app it would like something like this:
app.post('/my-node-endpoint', function(req, res) {
// Store the values we are posting as JSON
// Start the post request
// On End tell the React component everything is ok
// Prosper
});
As always, thanks for any help that is offered.
Your thought process looks right to me.
If the API you are calling is from a different domain, you will have to build a wrapper on your node server like you did here. Unless the external API supports cross-origin requests with no domain restrictions (such as MapBox web services), you will have to do this.
Several improvements to your code:
As far as I know, you can use React.findDOMNode(this.refs.testData).value instead of this.refs.testData.getDomNode().value. getDomNode() is deprecated in v0.13.
For all the AJAX calls, you can use the Store concept in Flux. The store keeps the states of the data, including updating data through AJAX request. In your React UI code, you just need to call the methods of the store, which makes your UI code clean. I usually create a store class myself without using Flux.

nodejs mobile development: how control navigation flow

I am a nodejs newbie and would like to understand the navigation flow when using nodejs to serve mobile applications.
Moible app
index.html
Show all users
Nodejs server snippit
var myData = {
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
};
res.send(myData);
Question: how do I display this data on another page (users.html)? I've worked with nodejs where I can just render to a specific path and it picks the appropriate Jade file but not sure how to do it since the html / js files are on the phone and not the server.
If you know of an example application I can just look through that code and figure it out.
Thanks for your help.
First of all you need to understand that your node.js is executed on server side, and all it can do - response on requests and do some logic, that stays on the server.
Then there is .html and .js that is sent to your clients (browser), and it is rendered and executed on client-side. This execution and logic is very different, and is focused to provide user interactions and render all sorts of data.
So all you need is be able to 'ask' server for data (request) and then get response, validate it in browser, if it is valid, you can render it using JS.
In order to make your life easier, consider using jQuery.
AJAX - to make requests to server and get response with data.
express.js - web framework for node, helps with routes.
And just generally - go and try things, experiment and it is better to understand whole picture or specific details frist, before you making any decisions.

Resources