socket.io undefined and refusing connection - html

I am using socket.io to display a message but when I run node server.js it does not console log any of the output message. I have attached my chat.html, server.js and main.js file to show the socket.io code.
chat.html
<script src="http://localhost:54159/socket.io/socket.io.js"></script>
<script src="js/main.js"></script>
server.js
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log('New web socket connection...');
socket.emit('message', 'Welcome to Chat Room!');
});
const PORT = 54159 || process.env.PORT;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
main.js
const socket = io();

OK, I guess I'll summarize the recommended changes our exchange in the comments:
Change this:
<script src="http://localhost:54159/socket.io/socket.io.js"></script>
to this:
<script src="/socket.io/socket.io.js"></script>
That removes the need for you to specify the port (which was incorrect anyway).
Change:
/public/chat.html
to:
/chat.html
so that it matches up with where your express.static() line is looking. For /public/chat.html to work, chat.html would have to be located in public/public/chat.html on your server's hard drive, but I assume it's not and it's likely in public/chat.html. Your express.static() line is pointing at public so that's the top of the tree it looks in. Any other paths in the URL are relative to that.
And, anytime you make a change in client or server code, make sure and restart your server to make sure all recent changes are being used.
If you're unsure at all about what port your server is running on, then look at the results of this when your server starts up:
console.log(`Server running on port ${PORT}`)
That will tell you port its running on. The brackets log reference to a port is probably brackets connected to the nodejs debugger which will be on a different port from your web server.

Related

Part of my website not rendering when pushed to heroku

I have a part of my website (react-app) that wont render when pushed to heroku, but it runs fine locally.
The heroku domain is https://notmicahclark.herokuapp.com/
it uploads successfully to heroku no errors
my repo is https://github.com/Scharite13/NotMicahClark.
the page is the /art page.
the code related to it is the art.js file and the images are in the public, and the object is on art_database.js
You've generated your build folder once. You've since done changes to your code but haven't generated a new build.
const express = require("express");
const app = express();
const port = process.env.port || 5000
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(port, () => console.log(`Server started on port: ${port}`));
here you can see that you are only serving the content which is in your build folder. It hasn't changed.
Go into your clients folder and execute npm build and move the generated build files into /build.

Failed to load resource: the server responded with a status of 404 (Not Found) issue in Nodejs app

I need help. I looked up the solutions here but still couldn't find it. So I'm practicing something in Goorm ide and I have come to a dead-end. I am trying to link main.js(which is in js folder) file by putting the script in the footer. But I'm getting an error which says
Failed to load resource: the server responded with a status of 404 (Not Found)
I also uploaded some png files in lib folder and I'm getting the same error after trying to access those in an ejs template.
Root folder consists of js, lib and views folder and some others which are not relevant.
To link the main.js in footer.ejs(which is in partials folder inside views), I used
<script type="text/javascript" src="../../js/main.js"></script>.
The png images which are uploaded in lib/images folder, I tried to access those from an ejs template in views so I used
<img src="../lib/images/image1.png">.
I am getting that error in both the cases. It would be highly appreciated if someone could help. This is how my root folder looks like -
EDITED:
This is the app.js code:
require('dotenv').config();
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var indexRoute = require("./routes/index");
var flash = require("connect-flash-plus");
var session = require('express-session');
// APP CONFIG
app.use(express.static(__dirname + "/public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.set('json spaces', 2);
app.use(session({
secret: 'boom',
cookie: { maxAge: 60000 },
saveUninitialized: true,
resave: true
}));
app.use(flash());
app.use(function(req, res, next) {
res.locals.error = req.flash("error");
next();
});
// routes
app.use(indexRoute);
app.listen(3000, function(){
console.log("Server has started");
})
Your Express configuration specifies that all of your static files will be accessed from the public directory:
app.use(express.static(__dirname + "/public"));
This means that any files you want to access in your web browser must be within this directory (or a subdirectory of it).
For instance, if you want to access main.js, and it's location in public/main.js, you would access it on the frontend like this:
<script type="text/javascript" src="/main.js"></script>
Note that on the frontend, you must not include the public/ prefix.

Run Node.js by passing parameters

I have a server running with Node.js and my question is, whether it's possible when running the server like I usually do (with the command node app.js) to pass parameters (eg. [UserID; IterationID;ProfileID]). Later I want to use these parameters to generate canvas (which I'm not sure how to read the parameters).
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8000;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + '/public'));
app.use('/images', express.static(__dirname +'/images'));
app.get('/', function(req, res){
res.sendfile('main.html');
});
app.listen(port, function(){
//console.log('server is running on ' + port);
});
app.post('/submit', function(req, res){
console.log(req.body.rank);
return res.sendfile('success.html');
});
Thank you very much in advance!
You can pass the environment parameters. Here is linux terminal command example:
YOUR_PARAM=param_value YOUR_PARAM2=param_value2 node app.js
Inside the code you can access those params inside process.env object:
console.log(process.env.YOUR_PARAM); // "param_value"
console.log(process.env.YOUR_PARAM2); // "param_value2"
This is usually done to define where application is running (local, development server, production server).
In my opinion it is the best to put the rest of the configuration in the JSON files and load them according to the application environment.
So basically first you define where your app is running and then based on that load the correct configurations from specified file. That way you can even share the configuration with the rest of the team over git.
P.S.
It is also worth mentioning that convention is to define process.env variables with capital letters in order to avoid overwriting some of the nodejs or system environment variables (if you console.log the process.env object you will see lot of configuration data in there).

WEBSERVER JSON API LOCALHOST

I want setup a simple webserver using JSON API(I Followed this tutorial).I have in this directory (C:\xampp\htdocs\server) 2 files:
server.js
node_modules(folder)
server.js
var express = require('express');
var app = express();
app.listen(3000, function() {
console.log('Chatfuel Bot-Server listening on port 3000...');
});
app.get('/*', function(req, res) {
var jsonResponse = [];
jsonResponse.push({ "text": "Hi. " + (Math.random() * 5 + 1).toFixed(0) + " is a lucky number..." });
res.send(jsonResponse);
});
So what is happening in the background?
After launched via terminal: node server.js
If the server gets a request it invokes code lines 8 to 12.
But it doesn't works! why?
Screens and more info here.
The problem is that you're serving node from your local computer, and the chatbot testing service is trying to connect to that running instance of node, and it cannot connect to your localhost.
In the example, they've used digital ocean to deploy the node application. Therefore, the running API is available at some real IP address.
So, if you want to do what they've done, deploy your node app somewhere and expose that particular deployment's IP to your testing framework, and then it should work.

Nodejs Express not loading script files

I am trying to run a angular app thru node-express.
1 File Structure
AngularNode
public
/core.js
/index.html
project.json
server.js
2 server.js
var express = require('express');
var app = express();
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
// listen (start app with node server.js) ======================================
app.listen(8000);
console.log("App listening on port 8000");
3 index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="./core.js"></script>
........
4 core.js
angular.module('MySystem',[])
.controller('AppController',['$scope',function($scope){
$scope.Name ="Testing Text";
}]);
When I tried to run this app using node server.js this, index.html file is getting loaded properly, however this is not detecting or loading core.js file. and I am getting following errors
Uncaught SyntaxError: Unexpected token < core.js:1
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.5/$injector/modulerr?p0=MySystem&p1=Error%3…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.5%2Fangular.min.js%3A19%3A381) angular.js:38
Now, when I open index.html file directly from explorer, this is working OR when same code I move from core.js to inline html, under <head> with <script> block it is working.
I am not sure, why core.js not detecting or loading when I run thru node.
Got the Solution with few modifications:
1 Added line in server.js
app.use(express.static(__dirname + '/public')); after line
var app = express();
2 Case correction(Capital 'f') for function from res.sendfile('./public/index.html'); to res.sendFile('./public/index.html');
Now I can see core.js is detected and working fine.
The app.get('*', function(req, res) { is a catch all rule for all get request and will also match the ./core.js request. So for the ./core.js your express app will also send the html file.
You should use express.static instead:
var express = require('express');
var app = express();
app.use(express.static('./public'));