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

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);
});
}

Related

Connecting frontend and backend MERN stack

How does the react client connect to the server via express? Many tutorials talk about Superagent and axios which is adding to my confusion. Are there any resources on server side routing in the context of react? thank you
In MERN stack, you do not necessarily have to think of the entire stack as a single entity. Mongo, ReactJS and NodeJS server can all work independently. And let us for easiness of understanding sake say all of them are on separate servers. That is we can have Mongo on one server, ReactJS on another server and NodeJS with express on a third server, then also it will be a MERN stack app.
How a MERN app work is as follows
For example, let us have an app that displays the details of all the students in a class. First, in the React app let us say you select a class, and then the React front-end will send a query to the nodejs server. The query will contain the particular class name. Now nodejs will send a query to the mongo db asking for the details of the students of that class which it will send back to the node server. The node server will then send the details to the front end and it will update it.
If you ask for connection as such, there can be no connection at all except for querying for data. Instead of using the reactjs front end you can use some other frontend and it will give you the same details. React, Mongo and Node, all are capable of working on their own in their respective fields.
Axios is a promise based HTTP client for the browser and node.js.
They are completely independent. Whether using axios, the native Javascript fetch, jQuery AJAX, etc...each of them runs in the browser and makes a GET/POST request to nodejs. You will have defined corresponding GET/POST routes within nodejs to respond to these requests and return JSON response data for them to consume.
I would start by forgetting about react altogether. Instead build an express API with various GET/POST routes that return JSON responses. Test with a simple client like postman. Once you have a handle on that, then start with a front-end Javascript framework to consume these services.
Here is a cut of my express+react api:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render('index', {myjson: "myValue"});
})
module.exports = router;
Basically I am sending the json string to index.jsx, where the frontend is rendered.
Also I've set in express as:
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', reactViews.createEngine());
So the express server knows where React is.
Checkout the npm package Express-react-engine.
All the elements of the stack can be used independently, React , Node.Js, and MongoDB.
They can be installed in different servers and the communication is by using Fetch, Axios or any other tool.

Pure NodeJS and GraphQL, no middleware

Is there any example code implementing GraphQL on NodeJS without using any other middleware like Express, Apollo, etc. Just pure NodeJS http server with GraphQL, and any SQL db.
upd: If someone interested, you can check out my implementation on github - pureGraphQLapi
Nothing prevents you from using Node.js and GraphQL only ; you will be writing a little more code though.
Create your HTTP Server with Node.js only
Listen to incoming requests and use POST json body (for example) to pass query and variables to graphql function

Passing Data from Node-Express backend to Vue component

I'm still learning Vue.js 2 so I do apologize if this question is a bit silly. I'm building an application using MongoDB, Node, Express and Vue. Normally I'd use a template engine such as Ejs where data passed through Express's res.render method can be readily captured in the template.
Is there a similar way to pass data from backend to the root Vue component? For example, normally, a get request fetches some data from Mongodb, express will render the template file and pass data to it.
app.get("/gallery/:id", function(res, req) {
var id = req.params.id;
database.findById(id, function(err, data) {
....
res.render("home", data);
}
});
Now my root Vue application is attached to html file. I'd like to be able to dynamically render the app with data returned from the database.
I've built an app before that streams data from an api and passed it to my Vue component via socket but I feel like using a socket in this case is unnecessary.
Use http. What's the problem? You can use XmlHttp, or a lot of folk seem to be using Axios. Trigger the call in the onload of your page, or use one of the vue lifecycle hooks. The very good vue docs don't have much to say about how and when to do this. We do it in the onload of the page, and we instantiate vue when the request for page data returns.
The question has already been answered, but I wanted to share my approach. I've been experimenting with rendering an object server side using res.render(), putting it in a div where display: none, and then grabbing the object on the client and passing it to Vue's data attribute.

Context IO node.js client library

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.

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