Syntax error in nodeJs file run - javascript

i am very new to nodejs
when i tried to run my first js file having following content
var http = require("http");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
with the command
$ node fullpath/filename.js
i am getting error thrown like below
Can anyone tell what is wrong. I am using nodejs appliction window

Please do not run the code in the REPL
[user#machine]$node
> node app.js
SyntaxError: Unexpected identifier
at Object.exports.createScript (vm.js:24:10)
at REPLServer.defaultEval (repl.js:225:25)
at bound (domain.js:287:14)
at REPLServer.runBound [as eval] (domain.js:300:12)
at REPLServer.<anonymous> (repl.js:417:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:210:10)
at REPLServer.Interface._line (readline.js:549:8)
at REPLServer.Interface._ttyWrite (readline.js:826:14)
Just run it in the command line
[user#machine]$node app.js
Server running at http://127.0.0.1:8081/

Related

Server crashes when making an API call

app.post("/", (req, res) => {
const origin = req.body.origin;
const destination = req.body.destination;
const urlOri = "https://api.openweathermap.org/data/2.5/weather?q=" + origin + "&APPID={mykey}"
https.get(urlOri, function (response) {
console.log(response);
})
});
I have written this code and I am getting this error:
Server started on port 443
events.js:292
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT 178.128.25.248:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
Emitted 'error' event on ClientRequest instance at:
at TLSSocket.socketErrorListener (_http_client.js:469:9)
at TLSSocket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -4039,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '178.128.25.248',
port: 443
}
This same code runs on one of my friend's pc same as expected, what to do?
I have tried to do the same via request and axios module as well and I got the same error.
Sorry guys I was using a proxy server.
I disabled it and now it's working fine

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.

node.js express permission error on linux

using arch with admin user account and no sudo on this script:
var express = require('express');
var fs = require('fs');
var app = express();
app.get('/lol', function(req, res) {
res.sendFile('second.html', {root: __dirname })
});
var port = process.env.PORT || 81;
var server = app.listen(port);
i get this error that didnt change when i changed the port or the url to trigger it
it instantly gives me this error after i run the command: node site.js
(the code above is site.js)
node:events:371
throw er; // Unhandled 'error' event
^
Error: listen EACCES: permission denied 0.0.0.0:81
at Server.setupListenHandle [as _listen2] (node:net:1302:21)
at listenInCluster (node:net:1367:12)
at Server.listen (node:net:1454:7)
at Function.listen (/home/{name}/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/home/{name}/Documents/web/demo/site.js:10:18)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1346:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EACCES',
errno: -13,
syscall: 'listen',
address: '0.0.0.0',
port: 81
}
if i run the script with sudo it works fine but i dont want to run it in sudo
beacuse i have to run it on a server with no sudo. any help?
Using port below 1024 without root permission is common issue. Try port bigger than 1024.

Node.js MongoDB Creating Database giving error [duplicate]

This question already has answers here:
ECONNREFUSED error when connecting to mongodb from node.js
(21 answers)
Closed 5 years ago.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err)
{
throw err;
}
console.log("Database created!");
db.close();
});
This is the error I am getting when executing this code in nodejs and trying to create a database, I was going through the tutorial in w3school, please help to solve this error--
C:\Users\n.patel\Desktop\Promotion\nodejs\application4success>node mymongodb.js
C:\Users\n.patel\Desktop\Promotion\nodejs\application4success\node_modules\mongodb\lib\mongo_client.js:415
throw err
^
MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
at null.<anonymous> (C:\Users\n.patel\Desktop\Promotion\nodejs\application4success\node_modules\mongodb\node_modules\mongodb-core\lib\topologies\server.js:3
29:35)
at emitOne (events.js:77:13)
at emit (events.js:169:7)
at null.<anonymous> (C:\Users\n.patel\Desktop\Promotion\nodejs\application4success\node_modules\mongodb\node_modules\mongodb-core\lib\connection\pool.js:280
:12)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (C:\Users\n.patel\Desktop\Promotion\nodejs\application4success\node_modules\mongodb\node_modules\mongodb-core\lib\connection\connection.js:187:49)
at Socket.g (events.js:260:16)
at emitOne (events.js:77:13)
Make sure that you have Mongo running on on port 27017
use this to verify
mongo localhost:27017

Cannot get my file to display through Node.js

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.

Categories

Resources