Context IO node.js client library - node.js

I'm using Context.io's Node.js client library to get the body of emails from my account which is done in my code below.
Once I have that data, I am confused as to how I would get them over to the front-end. I'm new to the whole MEAN stack, and from my research of the basics, I have gathered that with Node, you can make the http calls, parse the json response and then write it to the server, but it seems as if I would have to make an API to then be able to call it from Angular and display it how I wish. I know that with other back-end languages like PHP, you can just write the code within the html, and not need a middle structure to get the info from PHP to the front-end. Is there an easier way than writing my own API in Node after having already made an API request to Context.io?
ctxioClient.accounts(ID).messages().get({limit:10}, function ( err, response) {
if(err) throw err;
console.log("getting responses...");
var messages = response.body;
console.log("message id is " );
console.log(messages.body);

You should implement the backend in JSON using something like res.json and make AJAX requests via Angular $http or something similar.

Related

NodeJs Express how to handle items(params) that sent from frontend?

Im new in backend development (using NodeJs Express).
Its very basic question (I didn't find any good tutorial about it)
Question is:
I have this line of code:
app.get('/test', function (req ,res){
res.send('test');
});
What I wanna do is: BackEnd only sends res to FrontEnd, if FrontEnd send some JSON first.
Like Backend will show Something to FrontEnd, only if FrontEnd send JSON first;
How to handle it? What code to write?
Or what to type in google search to find this kind of tutorial
You are building a REST API with node. In REST we don't keep states. When we receive a request we process and respond. In the Front end, you can do wait until the response is received. use promises, async-await or callbacks to wait until the response in the Front end. Use these methods to connect with back end from front-end axios, fetch. To process the incoming JSON body use body-parser. Based on the request body you can process and send the response. PS: Every request should be given a response. That's how REST behaves.
In Query
yourbackend.com/test?message=welcomeToStackOverflow
This is how you can access with in query:
const {message} = req.query;
console.log(message);
// welcomeToStackOverflow
In Params
yourbackend.com/test/:message
This is how you can access with in params :
const {message} = req.params;
console.log(message);
// welcomeToStackOverflow
Here you have working example : https://codesandbox.io/s/trusting-rosalind-37brf?file=/routes/test.js

How to call 3rd party api like Gandi.Net from Node (server.js)

I am new to Node.Js I am creating an Mean Stack application, in which I want to call 3rd party API Gandi.Net from My Node.js code.
My Node.Js plus Express Application is getting use to make rest based API which is getting consume by my Angular client.
I found a little bit help from this link https://github.com/baalexander/node-xmlrpc. ut not so much.
Do I need to make new server for XML-RPC?
If any one have did this kind of work, then any sample application will help a lot.
If any one have made any http call from node application then sample application will help.
It's quite easy to make an http call from the node server.
You can use the request module.
The documentation has tons of examples as well.
A very simple example from the module itself
var request = require('request');
request('http://www.google.com',
function (error, response, body
{
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});

How can I send information from NodeJS server to client side?

For example, I want to signal to the client side that a username sent via the POST method in an HTML form already exists in my database.
I know how to recuperate POST data with body-parser and I know how to look it up in a MySQL database.
I know that I could use Ajax to write an error message directly on the form. What does my NodeJS server need to send and how does it send this information?
I've searched through numerous tutorials and I just found solutions where they send a new HTML page. I want to keep my web page the same and use functions like appendChild() to post the error message.
There are a couple of ways you could send data from server-side, so NodeJS, to client-side - which I assume in your case would be some JavaScript file like main.js that handles DOM manimulation.
So, the 1st way you could send data is through a templating engine like Handlebars, for example. There is an easy to use module for express you could get here: hbs.
Now to quickly summarize how an engine like that works, we are basically sending an HTML file like you probably saw in the tutorials, however, a templating engine like Handlebars allows us to send actual data with that file dynamically, so what we would do is render a specific Handlebars template (which in core is just HTML), and pass in a JavaScript object to the render call which would contain all the data you want to pass into that file and then access it in the .hbs file.
So on the server-side, we would write something like this, assuming we have a file called home.hbs and set up Handlebars as the templating engine:
router.get('/home', function(req,res) {
var dataToSendObj = {'title': 'Your Website Title', 'message': 'Hello'};
res.render('home',dataToSendObj);
});
And access in home.hbs like this:
<html>
<header>
{{title}}
</header>
<body>
message from server: {{message}}
</body>
</html>
Now, the issue with this approach is that if you wanted to update the data on the page dynamically, without having to reload the page, using a templating engine would not be ideal. Instead, like you said, you would use AJAX.
So, the 2nd way you could send data from your NodeJS server to the front-end of your website, is using an asynchronous AJAX call.
First, add a route to whatever route handler you are using for AJAX to make a call to. This where you have some logic to perhaps access the database, make some checks and return some useful information back to client.
router.get('/path/for/ajax/call', function(req,res) {
// make some calls to database, fetch some data, information, check state, etc...
var dataToSendToClient = {'message': 'error message from server'};
// convert whatever we want to send (preferably should be an object) to JSON
var JSONdata = JSON.stringify(dataToSendToClient);
res.send(JSONdata);
});
Assuming you have some file such as main.js, create an AJAX request with callbacks to listen to certain event responses like this:
var req = new XMLHttpRequest();
var url = '/path/for/ajax/call';
req.open('GET',url,true); // set this to POST if you would like
req.addEventListener('load',onLoad);
req.addEventListener('error',onError);
req.send();
function onLoad() {
var response = this.responseText;
var parsedResponse = JSON.parse(response);
// access your data newly received data here and update your DOM with appendChild(), findElementById(), etc...
var messageToDisplay = parsedResponse['message'];
// append child (with text value of messageToDisplay for instance) here or do some more stuff
}
function onError() {
// handle error here, print message perhaps
console.log('error receiving async AJAX call');
}
To summarize the above approach using AJAX, this would be the flow of the interaction:
Action is triggered on client-side (like button pressed)
The event handler for that creates a new AJAX request, sets up the callback so it knows what to do when the response comes back from the server, and sends the request
The GET or POST request sent is caught by our route handler on the server
Server side logic is executed to get data from database, state, etc...
The new data is fetched, placed into a JSON object, and sent back by the server
The client AJAX's event listener for either load or error catches the response and executes the callback
In the case of a successful response load, we parse the response, and update the client-side UI
Hope this is helpful!

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!

Node.js works with CouchDB and Backbone.js, How json is being served?

I am trying to build a test app for learning Node.js. I came from wordpress background and Apache has setup most of backend logics for me. But now, I have to build my own. I have a question about how to serve JSON files from server side to client side. What is the workflow -- Backbone.js handle all client side Data manipulation, send/save/get/fetch from couchDB, serve JSON object from NODE.js backend?
I am using Express Microframework for building HTTP server, installed the Cradle middleware for access CouchDB NoSQL database. I successfully posted the data from Client side HTML (Jade template engine) to the CouchDB Database/Document and able to retrieve those data back from Server through Cradle middleware. Things work out great. But it was all done by Backend.
I want to use Backbone.js for my client side Javascript. Backbone.js is looking for JSON object which send back from the HTTP server. Cradle Middleware is able to create JSON object but only send them directly to the Jade Template, I could use Jade syntax for loop to iterate over the data object but it still not meet what I want for Backbone.js handle all the data entry. I realize that I need to get JSON obj via ajax ( either a file generated by HTTP then send back to the client OR send straight object to the client ). Cradle Middleware could not do that.
I did more research on this questions. I tried CouchApp, it does what I need. Using the Backbone.js to handling all the data, send/save/fetch data from CouchDB database. But it is a running in CouchApp, it is not an Express Node.js workflow. ( Maybe I am wrong or just do not how it work )
I tried backbone-couchdb.js. I read through the Details and still do not know it is going to help me to get what I want. ( Maybe need more tutorial or code example ). I am still thinking that I need a Backbone CouchDB driver to connect those two and somehow serving them by NODE.js backend.
Is there anybody who could tell me about how JSON file is being served by Node.js, how backbone.js interact with data save/fetch/get from CouchDB? What is the best practice / workflow? Other good resources, code examples, useful tools?
Cradle Middleware is able to create JSON object but only send them directly to the Jade Template
This is incorrect. You can just send the json back without rendering a template.
function(req, res, next){
db.view('user/byUsername', { key: 'luke' }, function (err, doc) {
res.send(doc); // or res.json(doc);
});
}

Resources