http Post and socket IO - node.js

now I am learning how to build single page web applications with node.js. When I come to the communication part between server and client, I am confusing about the difference between http post request and web socket communication
Here is my understanding:
Web socket like socket.io is asynchronous communication while POST is synchronous communication method.
socket.io is mainly used in dealing with real-time task like html games or dynamic online chatting, or boradcasting some informations.
for validating forms when some user sign up for certain website, it is really good to check instantly if the user name is already been taken or not, I think it is using socket.io to achieve that.
for example in a login page, after I press the username and password, then press 'login' button, I could just use emit things in socket.io to transfer a JSON file with these information. when we checked these information and send back a flag string like 'true' or 'false ' to indicate if the login is success or not.
So my question is:
Why we still use HTTP POST for login and signup ?
Is socket.io better than HTTP POST ?
Why not replace HTTP POST with socket.io ?
P.S for some large files, I have not go into these parts, so I have no idea.
Here is some additions:
After reading a similar question I find I seem to assume that WebSocket is a replacement for HTTP. It is not. It's an extension.
I think this asnwered my third question Why not replace HTTP POST with socket.io.

Related

What is the need to verify reCaptcha in the server side?

I am implementing google reCaptcha. In the Google documentation, they say the way to do it. The documentation suggests server side validation of captcha. I wanted to know why we need to verify it in the server side as it is already verified in the UI side from the google server. Is it a suggested to implement captcha in the UI side alone with no validation in the server? What are the problems(if any) if done in UI alone.
a example would be: you're creating a register form and want to prevent bots to create a account on your site, you need to verify it serverside, because in the background you're sending a request which will look something like this:
POST /register 1.1 HTTP
Host: www.example.com
{"username":"example","email:"hey#gmail.de","captcha-token":"123984f729340fmu2q34f9"}
and if you dont send the captcha-token with the request or the server doesnt validate it, this bot could just spam this request without loading the frontend page. Please mind in head, that bots dont visit your "UI" (frontend page). Just verify everything serverside like text length, bad characters, rate limits...

Node.js send variable to client

I have a small Node.js HTTP server that does requests to a mongo database (with the mongoose module).
What I want to do is query the database, store it in a variable (array) and send it to the client.
Because ideally, when the user clicks on one of the buttons on the html page, the JavaScript will pick-up the event and change the appearance of the website by showing calculations based on data that is stored in the database.
The only way I could come with was just "transferring" the database content to the client browser but if anyone can come with another solution that would be fine too !
So basically my question is :
How can I pass a variable from the Node.js server to the client browser when serving a page ?
Thank you in advance !
If you will be doing more than a couple of these types of transfers, I recommend looking into Socket.IO.
It's a layer that provides quick and easy communication between Node.js servers and web front-ends, by abstracting web sockets when available, and falling back to other transports (such as JSON-P or Flash) when it's not available. Basically, you would call io.emit('something', {yourdata: here}), and it is easily received on the other end. All of the serialization is done for you.
http://socket.io/
Give their demo a shot to see how it works.

Redirecting to new page in response to Socket.IO event

I'm developing a multi-page web application with Express that has chat functionality (powered by Socket.IO). Users can invite others to a private shared chatroom (that also has other components like a shared drawing board). I'd like to redirect both of the users (inviter and invitee) to a different URL upon completing the invitation transaction.
Since socket.io doesn't have access to the request and response objects of my routes, I attempted to pass my instance of socket.io into my route handling. Issues of duplicate event handlers piling up on page refresh aside, Express throws an error when trying to do a redirect after the response has already been sent (this makes sense).
It seems like the only way to achieve this would be to have the redirect occur on the client, with the new chatroom URL being passed to each from Socket.IO. Relying on the client for state transfer seems too fragile, though.
Are there any other options? What is the best way to implement what I'm after?
I'm not so sure it would be too fragile to do in the client. Just send the URL over the socket and either do window.location.href = redirectUrl or $('div').load(newContentUrl) with jQuery.

Node.js+Socket.io: Templating # server or browser? Load content via ajax or socket.io?

I already asked a similar question but this one is a bit different/specific:
I'm about to start development of a social community site (for a local user group) with features like timeline, IM/chat, forums, ...
Node.js and socket.io (or now.js) on the backend. jQuery (and maybe backbone.js or similar) on the front end. Content is loaded via socket.io or ajax and navigation via url hash.
There are 2 things where I just can't decide which way to go. I hope here are some people who can provide some good or bad experience.
Templating on server or in browser? I'm not sure if it's better to load a complete html site + live updates (also in html) for timeline, forum posts, IM/chat, ... or use something like a REST api via ajax or socket.io and do the templating on the client site. I've never done that before. You need to download the templates, etc, etc. Has anyone experience in this? There are also 2 ways to implement a rest-like api: E.g. request a forum post, then request the user associated to that post and so on (just like server side MVC) - or - request a forum post and the server answers with all needed information.
Load content via ajax or socket.io? I'm definitively using socket.io or now.js for real-time communication (IM, chat) and pubsub (on mainpage -> subscribe to new timeline updates, on a forum topic -> subscribe to new posts). But should I also load HTML (or provide a REST-like API, see question 1) through the socket? When people open forum posts in tabs (which I usually do a lot) that would mean a lot of socket connections. And I'm not sure how long it takes for a websocket to establish connection.
So there a 4 ways to do this:
HTML via AJAX - probably the most stable way that doesn't need a lot javascript to do the templating - Browser can use open HTTP connections to request stuff.
HTML via socket.io - The websocket must be established to load content (may be slower)
API via AJAX - as it probably needs more requests as HTML via AJAX there might be some HTTP header overhead + you need to authentication in each request- I'm not a friend of too many ajax requests.
API via socket.io - Socket must only be authenticated only once and you can request API objects on the fly. However I would still load templates and js via HTTP for browser caching.
I know this is a huge post but I'm debating for many days now and just can't decide as it would be a lot of work to switch the system once started developing. This is not a public project, it's limited to ~10k-15k local people and thus must not be that perfect, a good opportunity to learn new things in my opinion (I'm completely new to node, classic PHP MVC + jquery dev here).
I think you should use a RESTful api on the backend, let the templating occur just on the frontend (maybe with Backbone) and only use Socket.IO for real realtime stuff (such as chat). It doesn't make any sense to use websockets for something like loading HTML, because it most likely never changes.
So my vote is:
1) HTML via AJAX
2) API via AJAX
3) Realtime communication, such as chat messaging (or other stuff that constantly changes) via Socket.IO
Though there really isn't a definitive answer, as it depends.
If you need to be search engine crawlable, you can NOT rely only on client-side processing. If your individual views are light, and/or you need to support mobile, you should have initial rendering server-side.
Currently, I would suggest using an API that both your client application and server-side can use. If you use node for the server-side rendering you can re-use a lot of the same logic, including the API client.
Going a few steps farther, if you look starting with the Yahoo flux examples project on github, you can use the same logic both client and server-side including rendering with React views. This is not an easy solution, and will take some work.
For interactive elements, server-side rendering can be minimal with your stores pushing an event wiring up via sockjs/socket.io when the client starts for your chat/im bits.
You will have scalability issues when it comes to running across multiple processes and will likely need a pub/sub chain backed by a db for longer re-connect cycles or missed IM messages. There isn't a magic bullet.
Right now, I like flux+react... When Angular2 comes out, it may have a better story for server-side rendering.

How does in-browser chat work?

Just curious. How exactly does chatting in a browser work? Usually if a user goes to a web page, his/her webbrowser requests the page content. A server produces output and sends it to the user's computer. But with chatting it's a little bit the other way around (well not exactly). It's not the user requesting a chat message from some server, but rather the server that sends it directly. Now this is really simple to achieve with a "normal" server, but the thing that the server sends it to a browser directly confuses me. The posting the message part is all clear, it's simple. You just post the data to the server with for example ajax or something. But how does the other computer instantly "know" that a message has been written to it? It must obviously be the server sending it to the other computer as soon as it has been written. But somehow that doesn't compute in my brain. In my brain, the browser only request things, it doesn't just get them. How exactly do you do that?
Take google talk in gmail for example. How does that work? How is it implemented?
There are some push technologies, such as Comet, but they're not widely implemented. Most of the time this is accomplished via polling at some small interval with AJAX and downloading any new messages that are available since the last downloaded message.
Take a look at Comet
Orbited is a good way to implement this, it uses comet methodologies. You can find a tutorial here.
Someone mentioned ajax polling, but comet is always better than polling. Well, that's just a sensationalist title, but comet is definitely more appropriate and can lead to less stress on the server side, with the right back-end.
It uses AJAX - a client-side javascript running on the GMail user's browser sends and receives the messages from the Google server, and writes them to the browser window - no reload of the page required.
I've develop a browser chat similar to facebook chat technology ( http://chatsign.com ). It is not a push technology but something better than polling, its call ajax long polling.
For more information about ajax long polling you can do some research or visit : http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery
Modern chat applications use SSE's (Server Sent Events: a feature of html5) to send new messages to browsers

Resources