I am new to UI framework development. Currently my requirement is to work with anuglarjs and nodejs. I know there are few more like me who want to know the exact use..
I am confused as where i need to use nodejs in my application. I tried to find a simple live demo example(plunker/jsfiddle) which used angularjs and nodejs but i couldn't find one.
Currently i have written a small module using angularjs, which hits the java controller class and saves/get the data and display the data on the webpage. Here i'm no where using nodejs. I tried to search in web to understand the use of nodejs with angularjs.
Any input's would be very helpful.
Below is the sample javascript code i implemented using angularjs.
myDataCOntroller.js
//some code here
$scope.submitFormData = function(myForm){
if(myForm.$valid)
{
MyDataService.saveOrGetData($scope.myReport).then(
function(response) {
$scope.myReport = response;
},
function(errResponse){
console.error('Errorr');
});
}else{
console.log("invalid form data!!");
}
}
myDataService.js
app.factory('myService',function($http,$q,$location){
var MY_SERVICE_URI = $location.protocol()+'://'+$location.host()+':'+$location.port();
var _repServiceFactory={};
_repServiceFactory.saveOrGetData = function(myData){
var deferred = $q.defer();
var url = appURL+'/saveOrGetData.form';
$http.post(url,JSON.stringify(myData))
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching data');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
PS: I know that Angularjs is client side, Nodejs is server side, both are using Javascript programming language.
What i want to know is, what is the use of nodejs and where is it used in real time??
If you are writing an AngularJS front end web application, you may never have to use NodeJS.
If you need tooling (build scripts to compile Sass, linters, etc) in your development or deployment process you can use NodeJS task runners like Gulp, Grunt or Webpack.
If you need to build a back end API, that stores and retrieves information, you can use Express or the whole MEAN stack.
* * * Also worth noting-- you mention hitting a Java class. If you are already using Java for the backend, then you probably won't be using any NodeJS for that purpose. If you were just shortening JavaScript to "Java", please note they are separate and distinct languages. * * *
Web dev has 4 primary parts:
Back-End: Node.Js (which will replace or work with your Java server)
Front-End: Angular.js (or React/Polymer/Vue/etc.)
Database: MongoDB (noSQL), mySql/Postgres (sql)
Routing/Server/Middleware: Express.js
For you to create an app that is realtime, you can use websockets, especially Socket.io (which works really well with and is built for Node.js)
WebSockets are essentially bi-directional (low latency) event-based tunnels where data can be passed from client-to-server, and server-to-client without the need to make an AJAX (tcp) request per message.
This paired with a strong data-binding architecture (API -> Angular Binding) allows for customizable single page views, where the same data can be used to create a view, and update the back-end modal when the data gets updated.
Related
Sorry for a nooby question. I'd ask it anyway!
I am playing around with AdonisJs. I understand it is a MVC framework. But I want to write REST APIs using the said framework. I could not find much help on the internet.
I have two questions:
Does the framework support writing REST APIs?
If yes to 1. then what could be the best starting point?
1. I've created 3 API projects with AdonisJS and think it's ideal for quick setup. It has many functions already included from start, supports database migrations and is pretty well documented in general.
You can create routes easily with JSON responses:
http://adonisjs.com/docs/3.2/response
Route.get('/', function * (request, response) {
const users = yield User.all()
response.json(users)
})
Or add them to a controller, and even fairly easily add route authentication with token protection (all documented):
Route.post('my_api/v1/authenticate', 'ApiController.authenticate')
Route.group('api', function () {
Route.get('users', 'ApiController.getUsers')
}).prefix('my_api/v1').middleware('auth:api')
2. Take a look at the official tutorial, you can probably finish it in about half an hour. http://adonisjs.com/docs/3.2/overview#_simplest_example
Start with defining some routes and try out echoing simple variables with JSON and just in regular views.
Move the test logic to Controllers
Read a bit more about the database migrations and add some simple models.
Don't forget the Commands and Factory, as you can easily define test data commands there. This will save you a lot of time in the long run.
Just keep in mind that you need to have a server with Node.JS installed to run the system on production (personally I'm keeping it running using a tool like Node Forever JS.
In order to create just a RESTful api you can use
npm i -g #adonisjs/cli
# Create a new Adonis app
adonis new project-name --api-only
I'm trying to write a very simple example application to familiarize myself with using MongoDB. Essentially, I'd like to have a single web page which queries a local MongoDB server, adding and removing content dynamically using jQuery. I have no problem at all throwing together the page layout and the jQuery, but I'm getting more and more confused by the MongoDB part of the equation. I understand that MongoDB is a server and runs remotely from the client, but for my example, I simply want to be able to query quickly and easily from client-side in-browser JavaScript:
$("#toggle").click(function() {
if ($(this).is(":checked") {
// add items from mongodb
addItems(mongodb.test.find({ age: { $gt: 5 }}));
} else {
$("#results").hide();
}
});
Is there a way to interface with MongoDB this way?
You need a driver to connect to a MongoDB server. The list of drivers is here:
http://www.mongodb.org/display/DOCS/Drivers
There is a JS driver, but only for server side JS - specifically node.js
Bottomline, you can't connect directly from a browser. You need a server side component.
As #balafi states you need a driver.
MongoDB does have a REST interface and infact there are drivers such as Mongoose that designed to create a fully functional REST interface for MongoDB.
This could be the route to go if you want to use MongoDB without all the hassle of setting up a server end. This way you would just ping a POST or GET call from JQuery with the specified params you want.
You can find more information on the REST interfaces here: http://www.mongodb.org/display/DOCS/Http+Interface
However I should warn you the built in one for MongoDB is extremely lacking and is only designed for extremely simple queries.
I've been working in the j2ee field for several years and tired of writing all those AJAX functions which downloading some data from server-side and render on the client-side.
Is it possible to only write javascript codes that run on both server-side and client-side.
like, if I need to develop a login page, I can write a piece of code kinda like this:
ORIGINAL CODE:
remote checkPassword;
function checkPassword(username, password){
if(existsRecord("select 1 from staff_t where user_name=? and password=?",username, password))
return true;
return false;
};
var main(){
var userName=$("username").val();
var password=$("password").val();
if(checkPassword(userName,password))
alert("Welcome, "+ user);
}else{
alert("sorry, wrong username or password.");
}
}
In the code above, javascript gets the data from dababase directly, isn't it clearer and easier to understand?
While this code actually runs on production mode, it is separated by an engine to two pieces:
SERVER-SIDE:
function checkPassword(username, password){
if(existsRecord("select 1 from staff_t where user_name=? and password=?",username, password))
return true;
return false;
};
CLIENT-SIDE:
var userName=$("username").val();
var password=$("password").val();
// 'checkPassword' has been translated to an AJAX function.
if(checkPassword(userName,password))
alert("Welcome, "+ user);
}else{
alert("sorry, wrong username or password.");
}
This way, we can use a single piece of code for a single business without separating them into java and javascript. The engine will separate the code and determine which parts should run on the server and others run on browsers.
I've searched all the internet, but didn't find any framework like that which can provide accessibility to database/EJB/WEBSERVICE.
Google Web Toolkit (GWT) enables us to write pure JAVA code for a browser-based application, but it seems a little clumsy for me. :)
Rhino is a javascript engine running on j2ee projects, but it doesn't provide any means to access both client-side data and server-side data.
does anyone know a framework like this, or is it possible to develop one all by ourselves? what's the pros and cons?
thanks.
Is it possible to only write javascript codes that run on both server-side and client-side.
Sure, drop J2EE and come join the node.js community
As for frameworks, no. You can't magically communicate between the two. The best I've seen is automated RPC like nodeQuery where the server sends DOM commands over RPC to a client.
Alternatively, who needs a server when you can write couchapps and serve HTML directly from your database.
A lazy solution to this is to use frameworks which have a direct binding between UI presentation and server object model. This makes it a lot easier to write validation only on server-side: you just specify the validation code in Java. AJAX makes this validation available on client side automatically (before the submit actually took place!)
If you think about it, the password example is very minimal. Most validation cases require more code and even more data. Suppose you validate the address of a user using a geographical database; will you push this full database to client side? No, you send the address to the server using AJAX and display the validation result to the user in realtime.
JSF uses this approach quite nicely (RichFaces, ICEFaces...)
We have just started our new assignment - web-based project. Before I get directly on to the question it would be necessary to explain about the project.
We are actually moving a product from desktop to web. This is it. All backend services are web services. Our choice of server technology will be .NET. As we are good with it and also client are equipped with it too. So, we will be doing all the server work in ASP.NET AJAX. PageMethod will be preferred choice to communicate with server (C# 3.0) and client (JavaScipt). There will be a real need of jQuery for parsing DOM and XML parsing. We do not to put effort to reinvent the wheel.
Now, there are things what we have to do and mostly it will be in JavaScript. We would like to package it in one.
E. John did a very useful session on 'Building a JavaScript Library' which is very useful. It surely keep in this way.
A fairly good amount of JavaScript engineers are here. And I would like to have their recommendations and suggestions before we start over.
Do you know some good references on JavaScript Library design? If you every made your own JS Library what you learned from it? Have you look into gmail/googledocs/facebook JavaScript? What have you learned from it?
Thanks.
Start off with something like this:
var yourNamespace = yourNamespace || (function () {
"use strict";
// private variables here
return {{whatever you want yourNamespace to be here}};
}());
To design a javascript library -
Identify what functions you write often.
Save them in a seperate .js file.
Keep a log or comment block on top
of the development version and
update to reflect the contents of
the file.
Done.
Use a webservice for connect to db and exec the queries..
Create SERVICE.JS, in this file call web service with jquery.ajax method
Create a DESIGN.JS, in this file do everythig about user ınterface (onclick, initialize,fill grids,combos etc)
Create a GLOBAL.JS, in this file create global variables for use everywhere(for example: UserId)
Create a HELPER.JS, in this file create useful functions for use anywhere(for example: function DATE_TO_STRING(_date) )
On this all .JS files use namespaces example for GLOBAL.JS:
(function () {
var GLOBAL = {
CurrentUserId:-1
}
if (!window.GLOBAL) { window.GLOBAL = GLOBAL; }
})();
Dont use ASP.NET components. Use html inputs,textarea etc
I'm starting to get my head around node.js, and I'm trying to figure out how I would do normal MVC stuff. For example, here's a Django view that pulls two sets of records from the database, and sends them to be rendered in a template.
def view(request):
things1 = ThingsOne.objects.all()
things2 = ThingsTwo.objects.all()
render_to_response('template.html, {'things1': things1, 'things2': things2})
What might a similar node.js function look like?
http://boldr.net/mvc-stack-node-js-ejsgi-scylla-mustache is a great little article with a full github example of a MVC pattern using dirfferent Node modules. It also lists alternate modules currently available. It answered this question for me better than http://howtonode.org/ which has some good tuts but I couldn't find anything on MVC there.
The easiest way to do this is with expressjs, which is an MVC framework for Node. Node is just what it says, evented I/O for the web.
The example on the http://expressjs.com should help with the basics but to answer your question directly.
var express = require('express');
var app = express.createServer();
app.get('/whatever', function(req, res) {
Things1.objects.getAll(function(things1) {
Things2.objects.getAll(function(things2) {
var options = { locals: { things1: things1, things2: things2 }};
res.render('thingstemplate.ejs', options); // or thingstemplate.jade or whatever
});
});
});
app.listen('80', ''); // port and optional hostname to bind
TowerJS is a popular MVC framework based on
MongoDB (database)
Redis (background jobs)
CoffeeScript
Stylus
Jasmine (tests)
jQuery
Site http://towerjs.org/
Source https://github.com/viatropos/tower
RailwayJS is a MVC framework, written in JavaScript based on ExpressJS and runs over nodeJS platform. It is inspired by Ruby on Rails framework. You can read about MVC architecture of RailwayJS here: http://jsmantras.com/blog/RailwayJS-Routing