How does Node serve client .js files? - node.js

For example, let's say we're trying to use socket.io.
In the html file served to the client, we include the following in the file.
<script src="/socket.io/socket.io.js"></script>
So two questions regarding this:
When the html file gets served to the client, it loads the socket.io.js resource (http://localhost:8080/socket.io/socket.io.js) without triggering the requestHandler in server.js (I have a log statement for any request that hits localhost:8080). How does this resource load on the client without triggering the requestHandler?
Where does Node find the socket.io.js resource that is required by the client?

Assuming you are using one of the basic Socket.io examples, this is because Socket.io overrides your handle with it's own and won't run your handler if the request is for something that socket.io manages.
When you call .listen(app) or .listen(80) it will set up all of the handlers it needs to process data and serve the client JS file.

Related

Is it possible to serve React from Node?

I'm new to back-end coding, and I'm struggling to understand exactly what a "fullstack" app would look like.
Is it:
A Node-Express server that serves index.html, which has <script src="main.jsx"></script> in it (If this is the case, how would the .jsx content get compiled into browser-ready javascript?)
A Node-Express server that serves some data (.json) + a frontend app (that you would initialize with Vite or CRA) that fetches from said server?
Both are currect , your server can serve content to the cliend (first case) or send data to the client (json , xml or etc).
Note that when you are working with react and .jsx component you have to build your project and server the html file (including js , css) via express server

Serving CSS stylesheets that are linked to HTML files via the link tag in Node.js w/o a framework

I have been teaching myself Node.js by way of trial & error. I built a simple server using the Node.js HTTP class. I figured out that I can read a file asynchronously and serve the data using the asynchronous fs.readFile(..., cbk) callback method. What I don't understand at this point is how respond with all the other resources that the requests needs.
// "./index.js"
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res){
fs.readFile('index.html', function(err, data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
For the sake of maintaining a single focus, I will use only Style-sheets as an example. Below is a super common link tag that demonstrates how I typically tell the server that the pages needs a specific CSS file. It works fine on the front-end side of things. But, how to I handle a request from a link tag on the the server's side of things (or on the backend)?
<link rel="stylesheet" type="text/css" href="/foo/bar/raboof.css">
Note: This is just a test project, but it doesn't use any frameworks, or even any modules (except for the dev-mod eslint). I would perfer to do this without 3rd party software/tools/frameworks etc...
Your nodejs server is not programmed to send any style sheets when the browser requests them.
A nodejs server, like you've created, serves NO files by default. It only serves files that you program it to serve. So, your nodejs server is programmed to do one thing and one thing only and that's to deliver index.html no matter what URL is requested from it.
So, here's what happens:
User enters some URL for your site
Browser sends your server a request for that page
Your web server delivers index.html
Browser parses index.html and finds style sheet links
Browser sends your server a request for a style sheet link
Your server sends it index.html
Browser realizes "that's not a style sheet" and you get no styles
So, for your HTML server to work properly, you have to add code to look at the requested URL and, if it's a style sheet URL, it needs to send the proper file for that stylesheet, not just blindly send index.html no matter what was requested.
Nobody says you need to use the Express library for this, but this is what it does. It makes it very easy to configure what gets sent when different types of requests are made. And, for requests of static resources like CSS files, it can even just be configured to automatically send them direct from the file system.
If you don't want to use Express for this, you don't have to, but then you will have to write your own code to serve the right data when different URLs are requested.
If you want to write your own code for this, you will have to create some sort of if/else or switch statement or table lookup that looks at req.url and then send the appropriate content that matches the requested URL. Then, when the browser requests your style sheet, you can actually send it the appropriate style sheet, not index.html. The same would be true for Javascript files, images, page icon, ajax requests or any resource on your server that your page references.
Because your server-side code is written to handle all.http requests and deliver the same html content, regardless of the path.
try adding some if-else logic inside your handler, and deliver appropriate file based on the request path.
something like:
if(req.path === "" || req.path === "index.html")
fs.read htnl file here
else if (req.path==="my.css")
fs.read css file
learn to use browser dev tools (F12), which shows you exactly which requests the browser is making, what it sends, what it gets back - amongst many other things.

node socket.io emit event on page load without loading page in browser

Hello is this possile to:
emit an event when i call a URL in browser or using Postman using node and socket.io
i want to do it without loading socket.io client.
inside my app.js or www file using express framework.
Thank you!

drupal - node.js integration

For a few days we'r trying to integrate drupal with node.js. but we couldn't connect with socket.io.js..
we're getting this error message from chrome console;
XMLHttpRequest cannot load http://mydomainname.com:8080/socket.io/1/?t=1340201859161. Origin http://mydomainname.com is not allowed by Access-Control-Allow-Origin.
and our backend settings are;
/**
* This configuration file was built using the 'Node.js server configuration builder'.
* For a more fully commented example see the file nodejs.config.js.example in the root of this module
*/
backendSettings = {
"scheme":"http",
"host":"mydomainname",
"port":8080,
"key":"/path/to/key/file",
"cert":"/path/to/cert/file",
"resource":"/sites/all/modules/nodejs/node_modules/socket.io/lib",
"publishUrl":"publish",
"serviceKey":"",
"backend":{
"port":80,
"host":"urb5.com",
"messagePath":"realtime"},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":["nodejs.server.extension.js"],
"debug":true,
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};
and also, in source code we have a script socket.io script,
like
<script type="text/javascript" src="http://mydomainname.com:8080/sites/all/modules/nodejs/node_modules/socket.io/lib/socket.io.js"></script>
this scripts build number is 0.9.6, but if we follow this path in ftp, there is a socket.io.js but its build number is 0.9.5
any suggestions?,
thanks..
The problem here, is that you are trying to load up socket.io from the server, but your front-end files are located in another domain space / server.
There is security regulations that does not allows cross-domain ajax and resources requests if they are not enabled by server.
So on server side where socket.io.js is coming from, you should add in page header something like this:
Access-Control-Allow-Origin: http://hello-world.example
Access-Control-Max-Age: 3628800
Access-Control-Allow-Methods: PUT, DELETE
This will allow you to share resource content with specified domain. And browser will not throw Access-Control-Allow-Origin error anymore.
As well, why you are trying to include js file through port 8080? If this is port that you bind your socket.io listener, then this is wrong, and you need to get js file through usual port (in most cases without defining, or 80).

Socket.io on Heroku: client-side code

I've been having trouble loading the socket.io library for my JS client code on a Node.js app hosted on Heroku.
For now, I have this line at the end of my index.html file:
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
But then, when I do socket = io.connect('http://myherokuapp');in my JS client code, I get an expected 'io is not defined' error.
Any idea how to correctly load the library on Heroku?
Thanks!
Ok so I finally found my way through. I'm sharing in case it helps someone.
I load the script in index.html this way:
<script type="text/javascript" src="http://myapp.herokuapp.com/socket.io/socket.io.js"></script>
It makes sense because the client-side library is actually loaded from the node server and shouldn't be pushed manually.
In my client-side JS file, I instantiate the socket this way:
socket = io.connect('http://myapp.herokuapp.com/');
Also, and this goes beyond the scope of this question, but you can't use websocket on Heroku for now. They have a little note about that here.
Hope this helps!

Resources