Loading Jade -> HTML via Websockets + NodeJS instead of AJAX - html

Wondering if there's a clean correct way to load html markup through websockets instead of through a $.ajax({...}) request. I'm somewhat new to websockets so I'm trying to figure out where it can completely replace AJAX and so on...
Right now I just create another 'post' router in my NodeJS app to load the html but I don't know if all of that is even neccessary.

you need websockets mostly if you want to maintain a bidirectional connection between client and server, useful for real-time applications (like chats, stock marketing, e-learning etc.).
if you need to load html mark down, you don't need to go back and forth from client to server many times to load the content and serve it, it will be much elegant and not wasteful way.
you can also use to get route and $.get ajax requests if you do not want to pass additional payload to the server.

Certainly you can pass data through websockets to your client from the Node.js server and, once on the client, just post it to the page.
If you are using socket.io, for example, you can emit an event inside your server with your generated html which will be received at client code:
On the server:
socket.emit('yourFiringEvent', variableContainingYourRawHtml);
On the javascript client:
socket.on('yourFiringEvent', function(htmlResult) {
$("#yourContainerId").html(htmlResult); //jQuery flavour ;-)
});
When your client code receives the event from server will load the data on variableContainingYourRawHtml inside of HtmlResult
If you aren't using it I recommend the use of socket.io library for websocket use, it's quite powerful and easy:
http://socket.io/

Related

How do I transfer data from Node.JS to an ExpressJS html?

I'm pretty freshly learning JavaScript, Node.JS and HTML. Planning to use ExpressJS to display content as follows:
`var app = express();
app.use(express.static(__dirname + '/public'))`
I want to have JSON formatted Data sent to the HTML page and want the user to be able to do requests to an API (that returns more JSON-Formatted Data, yay) and have the results displayed - if possible without reloading the page.
As I said I'm pretty new to this - so any resources or hints would be very appreciated.
On a sidenote, I am trying to stay at NodeJS because I want to access a MySQL database later on.
This is a very general question, but here is some information to get you started in the right direction.
Planning to use ExpressJS to display content as follows:
var app = express();
app.use(express.static(__dirname + '/public'))
Okay, but this doesn't explain how you are going to serve content. If you are just using Express to serve static documents, then this will work. It may be worth your time to get started using a view engine such as EJS or Jade. EJS is usually easier to learn because there is no special syntax, you just wrap plain javascript in <% %> tags. There are a multitude of tutorials on using both of these view engines.
I want to have JSON formatted Data sent to the HTML page
If you are sending static content, you need do nothing more than make a fetch request or xhr request. I recommend getting familiar with fetch first, as it is generally easier to work with than xhr.
With the promise that is returned from that fetch request, you can have some javascript loop through the information and create HTML elements using document.createElement() and insertBefore(). Using this method will not require a page refresh.
Of course, this is just how you would do it with Vanilla JS, and for something like this, there is no need to go bigger. But eventually it becomes easier to use a library like React to create an SPA.
I want to access a MySQL database later on.
Learning how to render json into a page now will likely simplify this step later on, since the Node Mysql driver returns a plain javascript object as a result of its queries, which can easily be sent to the client using something along the lines of res.send(JSON.stringify(results).
There are a multitude of tutorials and github repos on these topics. I recommend doing a little bit of research before diving in, but it all comes down to how much time you spend writing code and debugging.

Preventing access to JSON data in an Angular app

I got a (Flask) backend powering an API that serves JSON to an Angular app.
I love the fact that my backend (algorithms, database) is totally disconnected from my frontend (design, UI) as it could literally run from two distinct servers. However since the view is entirely generated client side everyone can access the JSON data obviously. Say the application is a simple list of things (the things are stored in a JSON file).
In order to prevent direct access to my database through JSON in the browser console I found these options :
Encrypting the data (weak since the decrypting function will be freely visible in the javascript, but not so easy when dealing with minified files)
Instead of $http.get the whole database then filtering with angular, $http.get many times (as the user is scrolling a list for example) so that it is programmatically harder to crawl
I believe my options are still weak. How could I make it harder for a hacker to crawl the whole database ? Any ideas ?
As I understand this question - the user should be permitted to access all of the data via your UI, but you do not want them to access the API directly. As you have figured out, any data accessed by the client cannot be secured but we can make accessing it a little more of PITA.
One common way of doing this is to check the HTTP referer. When you make a call from the UI the server will be given the page the request is coming from. This is typically used to prevent people creating mashups that use your data without permission. As with all the HTTP request headers, you are relying on the caller to be truthful. This will not protect you from console hacking or someone writing a scraper in some other language. #see CSRF
Another idea is to embed a variable token in the html source that bootstraps your app. You can specify this as an angular constant or a global variable and include it in all of your $http requests. The token itself could be unique for each session or be a encrypted expiration date that only the server can process. However, this method is flawed as well as someone could parse the html source, get the code, and then make a request.
So really, you can make it harder for someone, but it is hardly foolproof.
If users should only be able to access some of the data, you can try something like firebase. It allows you to define rules for who can access what.
Security Considerations When designing web applications, consider
security threats from:
JSON vulnerability XSRF Both server and the client must cooperate in
order to eliminate these threats. Angular comes pre-configured with
strategies that address these issues, but for this to work backend
server cooperation is required.
JSON Vulnerability Protection A JSON vulnerability allows third party
website to turn your JSON resource URL into JSONP request under some
conditions. To counter this your server can prefix all JSON requests
with following string ")]}',\n". Angular will automatically strip the
prefix before processing it as JSON.
For example if your server needs to return:
['one','two'] which is vulnerable to attack, your server can return:
)]}', ['one','two'] Angular will strip the prefix, before processing
the JSON.
Cross Site Request Forgery (XSRF) Protection XSRF is a technique by
which an unauthorized site can gain your user's private data. Angular
provides a mechanism to counter XSRF. When performing XHR requests,
the $http service reads a token from a cookie (by default, XSRF-TOKEN)
and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript
that runs on your domain could read the cookie, your server can be
assured that the XHR came from JavaScript running on your domain. The
header will not be set for cross-domain requests.
To take advantage of this, your server needs to set a token in a
JavaScript readable session cookie called XSRF-TOKEN on the first HTTP
GET request. On subsequent XHR requests the server can verify that the
cookie matches X-XSRF-TOKEN HTTP header, and therefore be sure that
only JavaScript running on your domain could have sent the request.
The token must be unique for each user and must be verifiable by the
server (to prevent the JavaScript from making up its own tokens). We
recommend that the token is a digest of your site's authentication
cookie with a salt for added security.
The name of the headers can be specified using the xsrfHeaderName and
xsrfCookieName properties of either $httpProvider.defaults at
config-time, $http.defaults at run-time, or the per-request config
object.
Please Kindly refer the below link,
https://docs.angularjs.org/api/ng/service/$http
From AngularJS DOCs
JSON Vulnerability Protection
A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n". Angular will automatically strip the prefix before processing it as JSON.
There are other techniques like XSRF protection and Transformations which will further add security to your JSON communications. more on this can be found in AngularJS Docs https://docs.angularjs.org/api/ng/service/$http
You might want to consider using JSON Web Tokens for this. I'm not sure how to implement this in Flask but here is a decent example of how it can be done with a Nodejs backend. This example at least shows how you can implement it in Angularjs.
http://www.kdelemme.com/2014/03/09/authentication-with-angularjs-and-a-node-js-rest-api/
Update: JWT for Flask:
https://github.com/mattupstate/flask-jwt

Connect to MYSQL database, retrieve data as JSON and send it to client side via AJAX

I am building an interactive web application with GWT, and I've come across a problem. The app is basically going to be a GUI for a database.
What I'd like to do:
Populate a MySQL server with data, and serve it via AJAX as a JSON file to my client side code.
The application life cycle should look like this:
Query on the client side -> Query the database -> serve up the requested information -> convert it to JSON -> Send back to client side via AJAX -> process on client side
I'd like to make this without refreshing the page, so the database querying should be ajax too.
If someone could point me to the right direction, I'd be really grateful. I've yet to find any good tutorials or examples to this type of problem.
Using GWT:
1° For Data-oriented app you will want to use GWT RequestFactory
2° If you want to stick to basic RPC here's what happens:
Fill up a form > Click on a button > make a call using RPC, passing a "shared" object as argument to your call > conversion from JSON to Java is handled by GWT > handle the request and make your query > convert the entity/DTO to a GWT "shared" object > your RPC controller returns the result > conversion to Java to JSON is handled by GWT > typically use a Celltable to display the result using a dataprovider, you won't need to reload the page.
If some parts of the process are unclear feel free to ask.
Don't use JSON unless there is some other reason you don't mention. A strong point of GWT is that you can use your entity code in your client side code so all of the client-server communication layer is hidden. Easiest way to do what you are asking:
Create #Entity annotated objects for each table
Create RPC service that exposes operations client needs
Implement database interactions with Objectify
Fetch your entities in GWT using RPC client

JSONP in non jsonp supported site

I have a requirement where I have to get data from another server .. The server supports only JSON and not JSONP. How can I get the data from the server using JSONP?
I am doing it in jquery..
Is there any other solution to it?
Kindly help me..
The reason why JSONP exists is to get around the cross-domain issue with Javascript. This basically means that javascript in your browser shouldn't be allowed to talk to webservices that's not on the same domain as your web application.
JSONP makes this cross-domain integration possible because your browser and the server have an "agreement". You give it a callback, and it gives you the result, wrapped in that callback. It expects to be called via javascript so there's less of a security risk involved.
Example:
You call http://www.abccorp.com/index.php?callback=somevalue
Without JSONP, you'd get back:
{ some: 'value' }
With JSONP:
somevalue({ some: 'value' });
If a server does not support this callback, it's just not possible (by only using javascript).
I recommend using a server-side programming language that can facilitate this call for you.
For example, you have a PHP file called index.php. Your javascript would call this file using an AJAX JSON request. In turn, it would call the server you need, get the results, and forward them to the javascript. Since you're not using javascript, this server-side programming does not need a callback (or agreement) like javascript does.

How to update mysql fields with Javascript

I don't understand. I have searched all internet forums but found nothing helpful. I am trying to update the numberOfLikes field on my postsTable in MySql when the user clicks on the like button. I know this is done through ajax but I am only familiar with prototype ajax and none internet forums state anything about it.
Here's the flow chart
1. On "seeForums.php" user clicks on the "like" link.
2. The like link has an id that triggers the function which updates numberOfLikes on my postsTable.
Thats it. Thats all I need. But I need it in a prototype ajax format, something like this.
function processLikes()
{
new Ajax.Request(theUrl,
{
contentType:"text/HTML",
onSuccess:updateLikesMySql,
onFailure:error
onException:error,
});
}
Helps are appreciated :)
You can't do this with Javascript alone as it is client side only, you'll need to get a server side language (e.g. PHP) involved as well.
The idea is that you send an AJAX request to your PHP file along with the data that you want to update, and your PHP file will handle inserting values into the database. That PHP file would then print an output (e.g. success or failure) which would be received in your Javascript so you can act accordingly.
You should know that the nature of HTTP (web) makes it Request/Response like.
So your backend code runs on the server,
And javascript and all frontend code run on the client.
Client has no access to your database, So you can't do anything to your database with Javascript.
Best thing you can do is ask your serve with javascript to update the database,
Make a server-side script available at some URL,
Then use ajax to call that URL.
In the server-side script, do the code which updates the database.