Cannot get my file to display through Node.js - javascript

I'm having problems with my node server. I'm trying to gather data from my coffees.js file which is in a routes folder by linking it to my server.js file. Both my server.js file and routes folder containg the coffees.js file are in my nodeservers folder. When I run the server.js (which is probably the problem as I think it is coded wrong) I get the following error:
Server running at http-00000000-:8080/
Listening on port 8080...
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Function.app.listen (/node_modules/express/lib/application.js:533:24)
at Object.<anonymous> (/home/ec2-user/nodeservers/simpleserver.js:19:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
[ec2-user#ip-10-74-151-139 nodeservers]$ ^C
[ec2-user#ip-10-74-151-139 nodeservers]$
My simpleserver.js file looks like this:
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8080);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8080/");
var express = require('express'),
coffees = require('./routes/coffees');
var app = express();
app.get('/coffees', coffees.findAll);
app.get('/coffees/:id', coffees.findById);
app.listen(8080);
console.log('Listening on port 8080...');
Anyone able to tell me whats wrong?

Remove either
server.listen(8080) or app.listen(8080).
I think you want to use express, so remove the first.

Related

I keep getting an error in my terminal, "error address already in use :::5000"

I'm following a node.js crash course and I get to the part where we are creating a server, but for some reason every time I try to run node index which is my js file name I'm getting the error:
address already in use :::5000
I've looked through similar problems and tried to kill that specific port but nothing seems to work.
if (req.url === '/') {
fs.readFile(
path.join(__dirname, 'public', 'index.html'),
(err, content) => {
if (err) throw err;
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
}
);
}
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
node index
node:events:504
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::5000
at Server.setupListenHandle [as _listen2] (node:net:1330:16)
at listenInCluster (node:net:1378:12)
at Server.listen (node:net:1465:7)
at Object.<anonymous> (/Users/zacdistant/Documents/GUIDES AND TUTORIALS/Node JS Crash Course/index.js:91:8)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1151:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1357:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 5000
}
If you are on a Mac, port 5000 and 7000 are already used by the Control Center with the AirPlay reveicer:
lsof -i :5000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
ControlCe 479 **** 26u IPv4 0xa2d0e96b616f779d 0t0 TCP *:commplex-main (LISTEN)
ControlCe 479 **** 27u IPv6 0xa2d0e96693d0bc65 0t0 TCP *:commplex-main (LISTEN)
To solve the issue you have to either change the port you use in your server like const PORT = process.env.PORT || 9000;, or turn off the AirPlay receiver. Also, if you want to check before hand is the port free, run netstat -anv -p tcp.
As #jamomani explained Mac uses port 5000 and 7000 that are used by the Control Center with the AirPlay receiver
To solve the issue you have to either change the port you use in your server like const PORT = process.env.PORT || 9000;, or turn off the AirPlay receiver. Also, if you want to check before hand is the port free, run netstat -anv -p tcp.

Cannot initialize Node.js on ec2

This is my first experience with Node.js.
Using an ubuntu ec2 instance on which I have installed Node, I am following this tutorial: https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8/
My index.js file looks like this:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 22
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.get('/', (request, response) => {
response.json({ info: 'Node.js, Express, and Postgres API' })
})
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
When I get to the part where I run node index.js, I get this error:
ubuntu#ip-172-31-87-85:~/riapi$ node index.js
events.js:183
throw er; // Unhandled 'error' event
^
Error: listen EACCES 0.0.0.0:22
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at Server.setupListenHandle [as _listen2] (net.js:1350:19)
at listenInCluster (net.js:1408:12)
at Server.listen (net.js:1492:7)
at Function.listen (/home/ubuntu/riapi/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/home/ubuntu/riapi/index.js:17:5)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
I found this SO issue: ExpressJS - throw er Unhandled error event
And when I tried a couple things from it, but without success:
ubuntu#ip-172-31-87-85:~/riapi$ netstat -tulnp | grep 22
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN -
tcp6 0 0 :::22 :::* LISTEN -
ubuntu#ip-172-31-87-85:~/riapi$ ps aux | awk '/node/{print $2}' | xargs kill -9
kill: (20586): No such process
Does anyone see what I'm doing wrong?
As mentioned in the comments, port 22 requires root privileges and is usually reserved for SSH.
Try replacing const port = 22 by const port = 8080 (port 8080 is the official HTTP alternate port).
Any unused port over 1024 should work (see https://unix.stackexchange.com/questions/16564/why-are-the-first-1024-ports-restricted-to-the-root-user-only).

Failed to torify node application

I'm writing a simple node server, and trying to torify it. But I got the following error, any idea?
It works fine when I go without torsocks, and I used default config for tor daemon.
$ torsocks node server.js
[Jan 26 09:38:40] WARNING torsocks[30933]: [syscall] Unsupported syscall number 293. Denying the call (in tsocks_syscall() at syscall.c:465)
events.js:160
throw er; // Unhandled 'error' event
^
Error: listen EPERM :::5000
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1259:14)
at listen (net.js:1295:10)
at Server.listen (net.js:1391:5)
at Object.<anonymous> (/home/test/src/heroku/ruten-helper/server.js:10:8)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
var http = require('http')
// Create server
var server = http.createServer(function (req, res) {
console.log("client connected")
res.end('HI!')
})
// Listen
server.listen(process.env.PORT || 5000)
I got it.
I checked the torsocks debug message, I see the following.
[listen] Non localhost inbound connection are not allowed. (in tsocks_listen() at listen.c:64)
And I changed my code to listen on localhost only, problem resolved.

Node.js Tcp server EACCESS

Using net to create a TCP server on Node.js on a windows machine
var net = require('net');
var host = 'localhost';
var port = '7171';
net.createServer(function(socket) {
console.log('CONNECTED - ' + socket.remoteAddress);
}).listen(host, port);
But Im getting this EACCES error even if I run the node console as admin with control shift click.
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EACCES
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1023:19)
at listen (net.js:1064:10)
at Server.listen (net.js:1132:5)
at Object.<anonymous> (E:\Xampp\htdocs\tibiajs\server.js:7:4)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
Since at windows I normally dont have to deal with these kind of privilegies issues I dont know what to do
You have your params backward:
.listen(host, port);
should be
.listen(port, host);
Also I'd probably pass the port number as a number instead of a string, but either appears to work.
Docs: http://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback
server.listen() takes a port, with optional host. Signature is listen(port, [host], [backlog], [callback]). I think this is what you want:
var net = require('net');
var port = '7171';
net.createServer(function(socket) {
console.log('CONNECTED - ' + socket.remoteAddress);
}).listen(port);

socket.io doesn't seem to be starting and doesn't recognize io.configure method

I am trying to get socket.io running with node/express (I have done this countless times - so I am pretty baffled). When I try to configure socket.io with the io.configure method I get an error:
io.configure(function() {
^
TypeError: Object #<Server> has no method 'configure'
at Object.<anonymous> (/home/yz/webdev/ground/app.js:377:4)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
My code is exactly how it says to do it on socket.io - but I'll post it just in case:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
//other declarations
app.use(...
passport.use(...
//some routes
app.get(...
app.post(...
io.configure(function() {
io.set('transports', ['websocket','xhr-polling','flashsocket']);
io.set('flash policy port', 10843);
});
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
...
});
});
The error gets thrown at the io.configure method - I have done this before with other sites, I don't understand whey it isn't working now. Thanks.
UPDATE
I was just reading here that io.configure doesn't exist anymore - however, I can't seem to get it working the new way either. Here is my new code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
//var io = require('socket.io').listen(server);
var socket = require('socket.io')({
'transports': ['websocket','xhr-polling','flashsocket'],
'flash policy port': 10843
});
var io = socket.listen(server);
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
...
});
});
I'm not getting any errors, socket.io just doesn't seem to be starting.
You're assigning io to a server, which is causing the problems when you attempt to call functions on io which are available from socket.io. Try replacing this line:
var io = require('socket.io').listen(server);
With this line:
var io = require('socket.io')(server);
The socket.io docs list a couple of configuration patterns you can take advantage of, and it is possible to create a server using socket.io. But since you're already creating a server, you shouldn't need to do it with socket.io.

Categories

Resources