Using socket io on webserver - javascript

I used socket.io on localhost:3000 for several tests. Now i tried getting it to work online for an hour but I’m making no progress.
server.js
const http = require('http').createServer()
const io = require('socket.io')(http)
io.on('connection' (socket) => {
socket.on('start_session', (data) => {
console.log('hey there')
})
})
app.js
const socket = io('http://localhost:3000')
socket.emit('start_session', session_id)
The server.js is running on a server, it’s in the same folder as my index.html and app.js, on my own device it’s working perfectly fine
What am I missing? Can this even be archived with using localhost? I searched for alternatives but it’s always localhost.
Thanks in advance

The path to the socket.io.js file is also not working, how do I find that out? Tried the whereis command, but that didn’t help.

Related

how to call expressjs endpoint from static html file in vercel

i have a very simple app with 1 /api/index.js server and 1 index.html file at the root.
index.js has a route app.get("/api/mystuff", () => {...})
index.html calls pings this route from a <script> with:
const result = await fetch("/api/mystuff")
all of this works locally, but when deployed to Vercel i get hit with a 404 from my request. the endpoint it's hitting is https://myvercelapp.vercel.app/api/mystuff and i'm getting a The page could not be found NOT_FOUND error. I don't know how to get this working, can someone steer me in the right direction?
thanks!
Based on the used tags I'm understanding you are using express with node.js.
Without seeing any of your code, I am guessing either your vercel.json isn't setup correctly (the guide explains this) or your index.js isn't setup correctly.
Vercel Guide on using Express
In that case, Vercel has a great guide on Using Express.js with Vercel.
In vercel's guide they have a section addressing using Standalone Express.
In this guide they use an index.js inside of an api folder.
The index.js file:
const app = require('express')();
const { v4 } = require('uuid');
app.get('/api', (req, res) => {
const path = `/api/item/${v4()}`;
res.setHeader('Content-Type', 'text/html');
res.setHeader('Cache-Control', 's-max-age=1, stale-while-revalidate');
res.end(`Hello! Go to item: ${path}`);
});
app.get('/api/item/:slug', (req, res) => {
const { slug } = req.params;
res.end(`Item: ${slug}`);
});
module.exports = app;
and the vercel.json which is what makes the whole project work.
{
"rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]
}
And finally, Adding a Public Directory which may explain more on how you can properly use Vercel with Express.
The Problem
The reason I assume that it's the vercel.json is the problem is due it working locally and not on Vercel. A good way to test this locally is using vercel dev.
Working Example
I've created a public example which may help you. Please check https://github.com/Crispy-Cream/vercel-with-express for the source code example
and the public website https://vercel-with-express.vercel.app/api

Why is my server showing error on the browser "This site can't be reached ERR_UNSAFE_PORT" even when it is running perfectly on the terminal?

I made a index.html file and index.js and server.js.
Inside server.js I have written the following code:
const express = require("express");
const path = require("path" );
const app = express();
app.use("/static",express.static(path.resolve(__dirname, "frontend", "static")));
app.get("/*", (req,res)=>{
res.sendFile(path.resolve(__dirname,"frontend","index.html"));
});
app.listen(process.env.PORT || 5060, ()=> console.log("Server Running..."));
No error is shown by the vs code and it is working fine in terminal but giving error msg when I am trying to load the application on chrome browser with localhost:5060 url with ERR_UNSAFE_PORT error. Please suggest some way to resolve this.
So, there are a bunch of ports which are considered unsafe by chrome browser which includes 5060 which you were specifying earlier. That's why earlier you were getting "ERR_UNSAFE_PORT" error when you were trying to load localhost:5060.
From the program perspective, there isn't anything wrong. And at first glance everything will look okay. The problem starts when chrome identifies the port and declares it unsafe. This is done by the browser to prevent XSRF so, that someone doesn't use chrome as a proxy to attack your services.
How do you know which are the ports we are not supposed to use? Refer at this link which provides a list of blocked ports on chrome browser - https://chromium.googlesource.com/chromium/src.git/+/refs/heads/main/net/base/port_util.cc
Final program would look like:
const express = require("express");
const path = require("path" );
const app = express();
app.use("/static",express.static(path.resolve(__dirname, "frontend", "static")));
app.get("/*", (req,res)=>{
res.sendFile(path.resolve(__dirname,"frontend","index.html"));
});
app.listen(process.env.PORT || 3001, ()=> console.log("Server Running..."));

Why does my localhost application on Node.js take so long/refuse to connect?

Why does my localhost:3000 application take so long to load? I have tried quite a lot of ways to solve this, such as:
Disable IPv6
Add localhost into the hosts file
Update npm and node.js to the latest version
The localhost doesn't load, and eventually, just stops loading and refuses to connect. I don't know why this is happening. I am using Microsoft Edge and Windows 10.
Here is my code:
//jshint esversion:6
const express = require("express");
const app = express();
app.get("/", function(request, response) {
response.send("Hello World");
});
app.listen(3000, function()
{
console.log("Server is listening on port 3000.");
});
Any Help would be appreciated. Thanks.
Edit: It used to load at least a little bit but never fully loaded, now it just refuses to connect. :(
The command line exited the node application, but from my side, it said it was still running. It must have just been a bug. I restarted my pc and it worked.

Using a node.js app with HTML

My goal is this: JS but server-side. My solution, the obvious, node.js. I've used node.js quiet a bit. Mainly for an application, not a web server. The only reason I need to do server-side JS is that I need to use a library that connects to the Discord API. So I have a little test .js file with my node.js in it. It just prints text if it works. Basic. What I need it to do is whenever someone goes to https://example.com/something, it runs the node.js script and if the script ends up with printing "hello", then https://example.com/something will say "hello".
I've done some research on this, I've found ways to deploy a node.js app, which I know how to do. I can't really find anything that I'm looking for though.
You can use express to run a webserver on nodejs
Install express by running "npm install express" in your project folder through command prompt
Create a app.js file with the following code
var express = require('express'); // load the express library
var app = express(); // create an instance of express
var child_process = require('child_process'); //load the child_process module
app.get("/something", function(req, res) { // Setup a router which listens to the site http://localhost/something
child_process.fork("./yourCodeFile.js"); // Launch your code file
});
app.listen(80);
Run node app.js to listen to web connections
Then you put your code into the yourCodeFile.js which has to be be in the same folder as the app.js file, even better you could just write all your code in the app.js code as long as you keep it inside the function inside app.get
You should take a look at cloud-based lambda functions and platforms like AWS Lambda, which run a script in response to an HTTP request. They are relatively new and the architecture used to support this is being called "serverless", which is a simple term, albeit a bit of a misnomer. There are various tools out there to help you build these systems, such as the similarly named Serverless framework, though you can typically still use more traditional server frameworks that you are probably more comfortable with. Either way, you are not responsible for managing any server, including starting it or stopping it.
In terms of constructing a response that you are happy with, you can of course respond with any arbitrary string you want. See the AWS example of a Node.js handler.
exports.myHandler = function(event, context, callback) {
callback(null, "Hello, world!");
}
Lambda functions can also return binary data and work well with static storage systems like Amazon S3. For example, the function can be run in response to the creation of static assets.
Your code should look like this:
const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
const pathName =url.parse(req.url).pathname;
if (pathName == '/something') {
res.end('Hello World\n');
} else {
res.end('Please visit /something \n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
You should run your file with node youfile.js And when you do curl http://127.0.0.1:3000 you will see
Please visit /something
But when you do curl http://127.0.0.1:3000/something you will see
Hello World

Express server basic example not working

I have node v7.4.0 installed on my remote server. I've installed the latest version of express which is 4.14.0 and I've set up index.js in my public_html. index.js is a copy of the official test online:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (request, response) => {
response.send('Hello from Express!')
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
When I run node index.js while in public_html, I get the expected results: server is listening on 3000. When I go to my server's domain name address or IP address on port 3000, I just get that it is "Connecting" and then it fails saying it took too long to respond (plus no response in the command line). What can I look into to fix this?
Looks like nothing is wrong with your code. It may be a firewall/antivirus; additionally, Try using another browser like Firefox. Make sure to use the loopback ip 127.0.0.1:3000 or localhost:3000 (same thing).
For me, it was because of the proxy. After disabling proxy for intranet, it worked fine.
For me it was because of the firewall settings. I added private network access and then it worked fine.

Categories

Resources