node server not running : exiting without any output - javascript

I've been messing around with codesphere lately and have a weird issue, at least to me:
my server.js:
const express =require('express');
const app = express();
const port = 8000;
app.get('/', (req,res) => {
res.send('Hi there')
});
app.listen(port, () => {
console.log("Running")
});
Upon npm start :
user#codesphere:app [master] $ npm start
personal_website#1.0.0 start /home/user/app
node server.js
then the output exits the server and returns to CLI
Output for running node server.js:
Another edit:
upper part, my package.json in their ide, lower part: package.json open in terminal (nano)
Now I actually think, it is save to assume they have trouble!

Related

Why is dotenv returning port as undefined when referencing through dotenv?

Yesterday, I had dotenv installed and referenced, and the Server was calling on port 4000 through env, I had Postman working and referencing the server but that stopped when I started my coding today, I have no idea what I changed, because I didn't think I had done anything.
My .env file is below:
PORT = 4000
NODE_ENV = DEVELOPMENT
DB_URI = mongodb+srv://<xxx>:<xxx>#products.<xxx>.mongodb.net/?retryWrites=true&w=majority`
My server.js file is below:
const app = require ('./app');
const connectDatabase = require('./config/database');
const dotenv = require ('dotenv')
//I'm switching between these two PORT constants to debug
const PORT = process.env.PORT
const PORT = 4000
const URI = process.env.URI
// environment variable setup (tutorial runs server through the root, hence the backend/...).
dotenv.config({ path: 'backend/config/config.env'});
// DB connection
connectDatabase();
app.listen(PORT, () => {
console.log(`Server running on PORT: ${PORT} as a ${process.env.NODE_ENV} project`);
});
When I run with the port number called directly through server.js the port loads as 4000:
But when I run through the environment variables I get undefined:
Not that it matters, but I turned off my VPN and restarted it. Not sure why it makes the error now.
On your server.js file, you are defining the PORT const using the process.env.PORT before calling dotenv.config(), because of that you env vars are not defined yet.
Try change your code to:
dotenv.config({ path: 'backend/config/config.env'});
const PORT = process.env.PORT || 4000;
const URI = process.env.URI;

"Hello World" Express does not show - I am shown my files instead

I am trying to build my first app. It's a calculator that measures the level of caffeine in your blood.
I copied the code from : https://expressjs.com/en/starter/hello-world.html (copied below), but it is not showing a page with the words "Hello World!".
Instead, I see 2 links to my 2 files within my folder "CaffeineCalc" (calculator.js + json file). I have copied below the page it shows me. [what my browser page shows instead of Hello World][1]
const express = require('express');
const app = express();
const port = 5500;
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
Let me know if you understand what I am doing wrong. Thanks!
[1]: https://i.stack.imgur.com/L6bnv.png
From The Picture you provide, it looks like a live-server running and not your NODE application
So To Fix That You Need to open the path of that dir in any terminal or command prompt and run
$ npm install
cause I can't see any node_module folder
then
$ node index.js
to start the node server
You can now open Your Browser to
http://localhost:5000
you need to use express urlencoded.
const express = require('express');
const {
urlencoded
} = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
app.use(express.json())
app.use(urlencoded({
extended: true
}))
app.listen(PORT, () => {
console.log(`Example app listening at http://localhost:${PORT}`)
})

Nodemon: app crashed waiting for file changes before starting... on Windows

I implemented express code with the mongoose database but I have faced "nodemon crushed" error for that I followed the below techniques but still, now I have faced this error.
Node version: v16.14.2
NPM version: 8.5.0
I have followed some steps to solve this issue and that is given below,
Open Windows Task Manager is given in the attached file
End Task (Node.js JavaScript Runtime)
But the problem is not solved!
Here is the code of server.js
const express = require('express')
const mongoose = require('mongoose')
const app = express()
mongoose.connect('mongodb://localhost:27017/my-students');
const studentRoute = require('./api/routes/studentsRoute');
//========> Routing Starting
app.use('/api/students', studentRoute);
//========> Routing End
//========> MongoDB Database connection and Check
const db = mongoose.connection;
db.on('error', (err) =>{
console.log(err);
})
db.once('open', ()=>{
console.log("Database connection Established!")
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>{
console.log(`Server running on PORT #${PORT}`)
})
Windows Task Manager where I end the task by clicking "End Task" of "Node.js JavaScript Runtime" but it was not solved the issue and the Task Manager file attached below,
Error screenshot is given below the attached file,
The problem is arising from this line
const studentRoute = require('./api/routes/studentsRoute');
check if you have this included in that file
module.exports = router
Reference: TypeError: Router.use() requires middleware function but got a Object

Does log4js require any extra code to work on an Apache server?

I'm trying to add Log4js-Node to a Node.js server running on Apache. Here's my code:
const path = require("path");
const express = require("express");
const log4js = require('log4js');
const app = express();
const logger = log4js.getLogger();
logger.level = "debug";
const port = 443;
log4js.configure({
appenders: { everything: { type: 'file', filename: 'logs.log', flags: 'w' } },
categories: { default: { appenders: ['everything'], level: 'ALL' } }
});
const server = app.listen(port, () => {
logger.debug("listening to requests on port " + port);
});
app.get("/log", (req, res) => {
res.sendFile(path.join(__dirname + "/logs.log"));
});
When I run the script on Node.js on my computer and navigate to localhost:443/log I see what I expect, which is this:
[2020-03-17T22:50:43.145] [DEBUG] default - listening to requests on port 443
But when I run the code on a remote server it crashes and I get this in the error page (with part of the path replaced by me with "[removed]"):
App 25925 output: at Server. ([removed]/index.js:27:9)
App 25925 output: at Logger. [as debug] ([removed]/12/lib/node_modules/log4js/lib/logger.js:124:10)
App 25925 output: at Logger.log ([removed]/12/lib/node_modules/log4js/lib/logger.js:73:12)
App 25925 output: at Logger._log ([removed]/12/lib/node_modules/log4js/lib/logger.js:90:16)
App 25925 output: at Object.send ([removed]/12/lib/node_modules/log4js/lib/clustering.js:97:15)
App 25925 output: [removed]/12/lib/node_modules/log4js/lib/clustering.js:97
App 25925 output: at Object. ([removed]/12/lib/node_modules/log4js/lib/clustering.js:8:13)
I'm using A2 Hosting which uses Apache 2.4.41. I opted for Node.js 12.9.0, and Log4js 6.1.2. The package.json should be the same on both my computer and the server, and I've run npm install on both.
Is this just an issue with Log4js and the server, or have I missed something somewhere?
This was actually a relatively simple fix. The path referenced by the last error in the stack trace is a Log4js module that implements clustering support through Node's "cluster" module. The line "8" referenced is cluster = require("cluster"). It's wrapped in a try/catch block like this:
try {
cluster = require("cluster"); //eslint-disable-line
} catch (e) {
debug("cluster module not present");
disabled = true;
}
The installation of Node.js on my computer came with the "cluster" module, however as far as I can tell, the server I'm using doesn't support it. Also, the version of Node I'm using on my computer is newer than what I'm using on the server (so I've now installed 12.9 on my machine). I believe the older version of Node doesn't bother trying to catch the exception and tries to load the cluster module, fails, and then throws the error.
So the simple fix was to comment out most of the "try/catch" block, leaving just the contents of "catch" like this:
// try {
// cluster = require("cluster"); //eslint-disable-line
// } catch (e) {
debug("cluster module not present");
disabled = true;
// }
If someone has a better fix, I'm open to suggestions.
The same response of #skittleswrapper,thx, it work for me.
I use Node.js 14.18.1 with log4js 6.3.0.
But i wondering what'is the necessary of this module 'cluster' and if we can
add it to our app in other way.

Connection error on curl in node.js

Hi I am currently trying to learn how to create a backend for my app but when trying to create a port 3000 and having curl it produces this error:
NodeTutorial git:(master) ✗ curl -v http://localhost:3000 - the connection is refused.
Please Help.
My code in my index.js is as follows:
var http = require('http'),
express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Seems your server has not started, try running below steps and see if you are able to connect or not:
Step 1: Create a directory which will contain all the files related to our app and execute npm init:
$ mkdir nodejs-server
$ npm init
Step 2: Install Express as a dependency:
$ cd nodejs-server
$ npm install --save express
Step 3: Create default entry point for Node.js i.e index.js, inside the same directory we created:
$ cd nodejs-server
$ touch index.js
Copy the content you have shown in your question in index.js:
var http = require('http'),
express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Step 4: Move to directory nodejs-server and start the app following below command:
$ cd nodejs-server
$ node index.js

Categories

Resources