Socket.io Connection Event Not Triggering - javascript

I am new to using socket.io and I have tried to set up a basic functionality according to the docs and youtube tutorials. My program is supposed to console log "New socket connection" when I navigate to the index page. However, the event is not triggering. Am I missing something? Thanks!
My app.js file
const express = require("express");
const socket = require("socket.io");
const http = require("http");
const moment = require("moment");
const app = express();
const server = http.createServer(app);
const io = socket(server);
app.set("view engine", "ejs");
// Set static folder
app.use("/public", express.static("public"));
app.get('/', (req, res) => {
console.log("Reached index page")
res.render("index")
});
app.get('/room', (req, res) => {
console.log("Reach room page")
res.render("room")
});
// Run when a client connects
io.on("connection", (socket) => {
console.log("New socket connection")
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running. Navigate to localhost:${PORT}`));
My index.ejs file
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<link rel="icon" href="../public/">
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="../public/index/css/index.css" />
</head>
<body>
click here
<script>
var socket = io(); // this line is supposed to be sufficient to trigger
// the socket connection
</script>
<script src="../routes/index.js"></script>
<script src="/socket.io/socket.io.js"></script>
</body>
</html>

The error resulted from my naming my variable 'socket' when importing the socket.io dependency. The socket param in the line 'io.on("connection", (socket)' is supposed to reference another socket variable not the one that I created. Common practice is to name the dependency variable 'socketio' instead of 'socket'

Related

Svelte don't load components with node.js

I want to build an application with Node.js and Svelte, but when I try to import a component it wasn't load.
Server side code:
const app = require("express")();
const http = require("http").Server(app);
const port = process.env.PORT || 8080;
const io = require("socket.io")(http);
const fs = require('fs')
const express = require('express')
app.get('/', (req, res) => {
res.write(fs.readFileSync('./pages/homepage.svelte', 'utf-8'));
res.end();
});
io.sockets.on('connection', function (socket) {
console.log('Utente connesso!')
});
http.listen(port, function() {
console.log("Listening on *:" + port);
});
Homepage.svelte:
<script>
import Component from './components/Component.svelte'
</script>
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SocialTree</title>
</head>
<body>
<Component />
</body>
</html>
Component.svelte code:
<div>
<h1>Test</h1>
</div>
Thanks in advice and sorry for bad english!

POST Request Firing Twice When Pressing Button After Page Reload

When pressing the button which sends a POST request, the request is fired twice but only after the page is freshly reloaded. The code's function is when the button is pressed, it sends a POST request to the url which then adds 1 to the JSON data value.
This is the button code in script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<button id="button">Click Me</button>
</body>
<script>
$("#button").click(function () {
$.ajax({
type: "POST",
url: "/updating",
});
});
</script>
</html>
This is the nodejs/url code:
const express = require("express");
const app = express();
const path = require("path");
const fs = require("fs");
const PORT = 1000;
// Sets public as static dir
app.use("/", express.static(path.join(__dirname, "/public")));
const filepath = "public/data.json"
const rawdata = fs.readFileSync(filepath);
// Addin 1 to JSON value
app.post("/updating", (req, res) => {
var data = JSON.parse(rawdata);
data.data++;
var newdata = JSON.stringify({
data: data.data,
});
fs.writeFileSync(filepath, newdata);
});
app.listen(PORT, () =>
console.log(`Server started on port ${PORT}: http://localhost:${PORT}/`)
);
});
JSON file:
{"data":29}
EDIT: The problem is due to nodemon. This error only occurs when I'm running on dev dependency which only includes nodemon.

ExpressJS: call a variable from .js file to index.html

I am using express#4.16.2
I want to call a variable from main.js to index.html
main.js:
const express = require('express')
const app = express()
var router = express.Router()
app.use('/',express.static('public'));
app.get('/main', function(req, res) {
res.send("index", {name:'hello'});
});
app.listen(3000, () => console.log('listening on 3000'));
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link rel="icon" href="images/favicon.png">
</head>
<body>
<<h1>{{ name }}</h1>
</body>
</html>
This is giving the following result on the webpage:
{{ name }}
Is there an http get method call that I need to make? What am I missing in between? Any help/hint/guidance would be highly appreciated!
Thanks
You have to use a template engine that let you replace variables in the view file with actual values, and transform the template into an HTML file sent to the client.
There are many view engines work in combination with express, you could choose one of them here: https://expressjs.com/en/guide/using-template-engines.html
I suggest you to use ejs since it's very easy to understand, Here is an example using it:
main.js
const express = require('express')
const app = express()
var router = express.Router()
app.use('/',express.static('public'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/main', function(req, res) {
res.send("index", {name:'hello'});
});
app.listen(3000, () => console.log('listening on 3000'));
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link rel="icon" href="images/favicon.png">
</head>
<body>
<!-- show name -->
<<h1><%= name %></h1>
</body>
</html>
You are using hbs syntax:
<<h1>{{ name }}</h1>
without ever loading the hbs view engine to render it.
example for hbs:
const express = require('express');
const hbs = require('hbs');
const app = express();
app.set('view engine', 'hbs');
app.get("/main", (req, res) => {
res.render("index.hbs", {
name: "hello"
});
});
app.listen(<port>);

How to get into html source code by rest request

I want to render some value of another website by fetching the HTML source data by REST request, console the value inside the span tag to my console log and render it to my HTML.
I can't managed to this by my current code, he receives the data before the DOM is ready and the specific san tag i need still not there.
My current code -
async function uiTagChecking() {
let url ='http://production.com:8000/loginPage#';
fetch(url)
.then(await sleep(6000))
.then(response => response.text())
.then(pageSource => console.log(pageSource));
}
The current source code I've fetched (this is before the DOM is ready and the needed span tag doesn't there yet)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>loading...</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="icon"
type="image/png"
href="images/favicon.png?v=9">
<!--<link href="assets/vendors/keylines/map/leaflet.css" rel="stylesheet">-->
<link href="XXXX" rel="stylesheet"></head>
<body>
<div id="app"></div>
<script src="assets/vendors/jquery.min.js"></script>
<script type="text/javascript" src="XXXX/index-c08574aac712ae81e016.js"></script></body>
</html>
The span tag i want to print and render -
<span class="version-for-qa">2.1.1</span>
But it appears only after the redirect is ended and the DOM is ready.
Technical info:
Node JS
JavaScript
HTML + CSS
My server file (express):
var express = require('express');
var cors = require('cors');
var app = express();
var path = require("path");
var fetch = require('fetch-cookie')(require('node-fetch'));
var btoa = require('btoa');
var http = require('http');
var fs = require('fs');
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, data , corsOptions) // callback expects two parameters: error and options
};
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/view');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index');
res.render('logo');
res.writeHead(200, {'Content-Type': 'application/json'});
});
app.use(cors());
app.set(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
});
app.listen(8033, function () {
console.log('CORS-enabled web server listening on port 8033')
});

How to link an existing Angular 2 app to Nodejs Server?

I have an Angular 2 app with this structure :
Structure of my Angular app
Then in server side :
Structure of server app
I see that there is 2 module dependencies folders, but I don't know which one I sould keep.
Here is my index.js file :
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
// Get our API routes
//const api = require('./server/routes/api');
const app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'client/portfolio')));
// Set our api routes
//app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/portfolio/src/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3001';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
When I start server I get this message :
Loading AppComponent content here ...
But it stops here and doesn't render the Angular application.
index.html file :
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<link href="node_modules/#angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/hammerjs/hammer.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>
Here's a good example of integrating AngularJS with NodeJS [open tutorial]
The trick is in this block
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});

Categories