How is the socket.io directory recognised - javascript

Online examples will usually include the socket.io library using
<script src="/socket.io/socket.io.js"></script>
However, I was wondering why this works even though I don't have a socket.io folder in my directory. Does running node index.js automatically create this socket.io folder?

The socket.io server listens for all incoming requests that start with /socket.io and "steals" those requests for itself, keeping them from the regular http server that the socket.io server is sharing.
When the socket.io server sees that this is a request for the socket.io.js file, the socket.io server then reaches into its own node_modules/socket.io/client-dist directory to get the client-side socket.io.js file and sends it back to the client.
If you look at what you will find in node_modules/socket.io/client-dist directory, you will see the file socket.io.js sitting there. That's the file that the socket.io server sends back to the client. This is client-side code, only on the server for the purposes of being sent to the client when it asks for it.
Keep in mind that responses to incoming paths with a nodejs http server are not necessarily about file directories on the server at all. If any code hooked up to the http server handles an incoming request, it can decide what it wants to send as the response, from anywhere in the server (whether from a file or not). Only specific middleware tools like express.static() look on the server's hard disk for a directory that matches the incoming request.

Related

NodeJs: How do I access the functions of my JavaScript backend from my HTML frontend?

Here is my HTML code in index.html.
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="stuff()">Click</button>
<script>
async function stuff() {
await connectToServer();
}
async function connectToServer() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(this.responseText);
};
xhttp.open('GET', 'C:/Users/myName/myFolder/index.js', true);
xhttp.send();
return;
}
</script>
</body>
</html>
Then, here is my backend code in index.js.
const express = require('express');
const axios = require('axios');
const port = process.env.PORT || 8080;
const app = express();
app.get('/', (req, res) => {
res.sendFile('C:/Users/myName/myFolder/views/index.html');
});
app.listen(port, () => console.log(`Listening on port ${port}`));
I can type node index.js on the command line and run this program and go to http://localhost:8080/ . When I do this, the html page shows up as intended. However, when I click the button in order to make a GET request to the server side, I get a console error saying Not allowed to load local resource: file:///C:/Users/myName/myFolder/index.js . I'm using Google Chrome by the way.
I know that it is a security thing, and that you are supposed to make requests to files that are on a web server (they begin with http or https). I suppose then, my question is:
How do I make it so that my server file index.js can be viewed as being on a server so that I can call functions on the backend from my frontend?
You have to make an HTTP request to a URL provided by the server.
The only URL your server provides is http://localhost:8080/ (because you are running an HTTP server on localhost, have configured it to run on port 8080, and have app.get('/', ...) providing the only path.
If you want to support other URLs, then register them in a similar way and write a route to handle them.
The express documentation will probably be useful.
You should not need to load your server-side code into the browser. It's server-side code. It runs on the server. It isn't client-side code. It doesn't run in the browser. The browser does not need access to it.
If you want to load some actual client-side JS from the server, then use <script src="url/to/js"></script> (and not Ajax) and configure express' static middleware.
Let's improve your current flow by separating your backend API process from frontend hosting process. While backend can, it's not good in serving static html files (especially for local development purposes).
Run your backend as usual, node index.js. But as soon as this command will become more complicated, you will probably want to use npm scripts and do just npm start)
Run separate server process for frontend. Check out parcel, snowpack, DevServer. It can be as easy as npx parcel index.html, but this command is likely to change frequently with your understanding of your tool features.
To call backend, just add an API endpoint to an express app (just like you already did for serving static content), and call it, using backend process URL.
Usually, you will see your app on http://localhost/ and it should do requests to http://localhost:8080/.
If for some strange reason you will want to dynamically download js file from your server to execute it, you just need to serve this file from your frontend hosting process. In order to do so, different development servers have different techniques, but usually you just specify file extensions and paths you want to be available.
After editing frontend files, you will see hot-reload in browser. You can achieve the same for node process with various tools (start googling from nodemon)
If you find this way of operating not ideal, try to improve it, and check what people already did in this direction. For example, you can run two processes in parallel with concurrently.

Node.js source code getting sent over to client

I'm building with Node.js locally and I came along a weird problem where if I typed localhost:8080/server.js, the whole server-side source code shows up in the browser (the server file's name is server.js). I guess what's happening is the server looks for server.js, finds itself in the directory and sends it over. That's a huge security risk right? Any way to solve it?
All my code files are present in the same folder; would changing that be the best way to fix the problem?
Since index.html and server.js are in the same folder then the server will send server.js when requested because it thinks it's javascript code for the client and not the server.
You should put the files you want to serve in sub folder (usually named public) like this:
public/index.html
public/style.css
then start the server using that folder with:
app.use(express.static("public"))

Node.js request.open("GET", "what.should.I.put.here.html/getAll", true);

So I've designed a majority of my website, and now I'm hosting it on a school based host service. I have two folders: a client folder that contains (basically) my html pages and my main.js page, and a server folder that contains the api that my main.js is calling to. When building, I would form my request as request.open("GET", "http://127.0.0.1:3000/getAll", true);. However, now that I am hosting it on a school hosting server, I'm not sure where I should call.
I've attempted using:
http://personal.psu.edu/dbp5208/PersonalWebsite/getAll
http://personal.psu.edu/dbp5208/PersonalWebsite/Server/server.js/getAll
http://personal.psu.edu/dbp5208/PersonalWebsite/Server/getAll
./getAll
request.open("GET", "http://127.0.0.1:3000/getAll", true); works on the school server, but only on my machine.
main.js file location: personalwebsite/client/js/main.js
server.js file location: personalwebsite/server/server.js
I suppose when working locally, you have to start the (Node.js-based?) server first, by something like npm run start or similar. When the server starts, it listens on port 3000 of localhost. That's what you're accessing.
The problem is - I think - that just uploading the server files does not start your server on the schools web server. The school server also has to run your server code, which then listens on a separate port. If your hosting service doesn't support running Node.js programs, it won't work.
The client works because the hosting service's webserver just delivers the files statically (a very basic task), but the JavaScript then runs on your browser.

How to create a nodejs websocket client

I'm working on a project where I need to have multiple node clients connect to a node server via websockets. The clients will send files to the server and the server will immediately distribute that file to all connected clients.
The problem I'm running into is connecting as a client in node. The built in ws module seems to only support server use. I've also tried the npm websocket client which allows me to use node as a client but I seem to only be able to send binary data without any other information like the filename, etc. using the sendBytes method.
Thanks for any suggestions.
Checkout the delivery package of npm.
It provides bi-directional file tranfer for node.js over socket.io.
https://www.npmjs.com/package/delivery

Node.js serve as a backend server for frontend app

I want to use Node.js run as a back-end server to serve front-end socket.io request.
The samples I found, seems can only run pages from Node.js server.
<script src="/socket.io/socket.io.js"></script>
The above js include is served by Node.js, how to include it if the front-end is a different application (e.g. PHP or static pages) ? Do I need to include all the dependent socket.io js libraries to make it work?
I'm currrently running apache/php alongside node.js/socket.io
If this is what you're trying to do, you can do it by serving socket.io on a different port than what apache is serving on (assumed 80).
In node.js, initialize the socket.io listener on a port 8080 for example:
var io = require('socket.io').listen(8080);
I believe, by default, socket.io will also serve its static client side files conveniently for you, such that in you html, you can:
<script src="http://yourhost:8080/socket.io/socket.io.js"></script>
Hope that helps.
It all depends on your server configuration. You may choose a path to Node.js backend that is not used by any other resource, and configure your web-server to serve everything else.
E.g. for Apache I used ProxyPass directive to enable connections to a local Node.js on a different port (to bypass local port restrictions), though may be not an option for your purposes:
ProxyPass /help/server/ http://localhost:8002/ connectiontimeout=1500ms

Categories

Resources