problem in connecting node.js and mongodb - node.js

I am building a website using node.js and mongoDB backend. Whenever I start running the server, frontend works completely fine but I am unable to connect to my database. Running mongod command always gives the message
{"t":{"$date":"2020-11-10T10:46:27.043+5:30"},"s:"I","c":"Network","id":23016,
"ctx":"listener","msg":"Waiting for connection","attr":{"port":27017,"ssl":"off"}}
I simultaneously executed npm start from the frontend and backend folders. The npm start from the backend folder gives
[nodemon] starting `node ./server.js`
Listening on port 8080
MongoDB connected
The npm start from the frontend folder gives
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.56.1:8080/
But whenever the open it, it gives
Cannot GET /
Is it because I couldn’t connect to the database? I’m fairly new to this. I can’t seem to understand the reason behind this. Can anyone please help me out?

Cannot GET /
means http://localhost:8080/ has no method defined in your app.
if you are using expressJs
in your server.js
add
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('No More error')
})
Here we are saying: send "No More error" whenever user opens "/" path.
i.e http://localhost:8080/ in your case.

Related

BASH: express command not recognized

I've read other forums on installing express, I have run
npm install express -g on command prompt as admin.
I did this command a few times and restarted my computer multiple times but Express is still not recognized.
Any help is appreciated.
Express isn't a web server; it is a framework for building web servers.
The express package doesn't provide anything directly executable.
The express documentation has a getting started guide.
If you aren't trying to do server-side programming using Node.js and just want an HTTP server, then the http-server package may be more your speed.
Assuming you’ve already installed Node.js, create a directory to hold your application and make that your working directory.
then follow the below command
npm init
follow step press enter and after
npm install express
make index.js file paste below hello work program.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Now you can run file using below command
node index.js
Open your broswer and enter URL : http://localhost:3000/
You can display Hello World!
You have successfully installed node js and express js program.

Basic express setup: not sending anything to local port

I created a frontend app and now trying to incorporate backend into it.
ON the same frontend app i added an index.js file in the root directory, and installed express and required it in index.js file.
Very basic setup as below:
const express = require('express')
const cors = require('cors')
const port = process.env.PORT || 3001
const app = express()
app.get('/', (req, res) => {
res.send({
greetings: 'hi'
})
})
app.listen(port, () => {console.log(`Server on port ${port}`)})
Server is successfully on port 3001 as per my terminal, however, on localhost:3001 I'm not seeing any json response I set up in app.get.
It says Cannot GET / instead. When i inspected in devtool(Network) it says 404.
This seems a very straightforward setup, but what could've gone wrong here?
i just figured why. I installed nodemon but my “start” script is “node index.js”. Should’ve used “nodemon index.js”
Working now with nodemon index.ks
Your code is fine, There are no errors, I tested it and it works as expected.
However few things to note, Keep Backend in Seperate folder/dirctory unless required.
Coming back to your question, There are many possiblity such as some modules are not installed properly
try running following command
//this will install if any library is currupt or not installed properly
npm i
if it doesn't work then try clearing cache
Also keep in mind, In nodeJS dev server does not automatically refresh changes, you need to restart server to see changes or you can use dev dependancy called Nodemon (this will auto restart server on saving changes)

Stop Past Express JS or React Builds from Running

I have been developing an app from the create-react-app starting project.
Today I have been doing the following on my local machine:
deploying my react app using react-scripts start
deploying my react app by using react-scripts build then either serving the build by either...
(A) using the [npm module serve][] as follows serve -p 4001
(B) or attempting to server using a express app like follows:
Express app:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(4001);
I've just restarted my computer and it's still serving the site at:
http://localhost:4001/ and I cannot figure out how to stop it.
I wouldn't mind the continuous deployment of this server but when I build the project again. The changes are not reflected.
The only work around I've come up with is to now deploy at port 4025 and use the Express method coded above.
How the hell can I get rid of this weird residual app that continues to run (via some react process) at port 4001?
I'd really like that port back for sake of keeping it the same across different machines :(
Turns out that chrome keeps react apps running even if the server stops providing them.
Go to chrome://serviceworker-internals and unregister them.

Heroku Node.js WebSocket Server

The Heroku Dev Center article Using WebSockets on Heroku with Node.js explains how to deploy the Node.js Websocket Test demo application, which uses Express.
However, I'm deploying a Node.js WebSocket chat server that doesn't use Express.
When I try to connect from Terminal with wscat -c ws://my-app.herokuapp.com/1, I get error: Error: unexpected server response (503). And, heroku logs returns code=H14 desc="No web processes running".
Why? How do I fix this?
Note: My Procfile is correct: web: node server.js.
Solution: Delete & recreate the app.
I changed the first line of the Node.js WebSocket chat server to:
var webSocketServer = new (require('ws')).Server({
server: require('http').createServer(function (request, response) {
response.end()
}).listen(process.env.PORT || 5000)
}),
Still didn't work.
Then, I deleted & recreated the Heroku app and deployed. Worked.
Then, I changed the first line back to:
var webSocketServer = new (require('ws')).Server({port: (process.env.PORT || 5000)}),
and redeployed. Still works!
Can you connect with curl -vD to get verbose information on what headers you server is sending?

Redis in Nodejs on Cloud9 IDE: [Error: Auth error: undefined]

Here is my code:
var express = require("express"),
app = express(),
server = require("http").createServer(app),
io = require("socket.io").listen(server),
redis = require("redis"),
env = {PORT: process.env.PORT || 8080, IP: process.env.IP || "localhost"};
client = redis.createClient(env.PORT , env.IP);
client.on("error", function(err) {
console.log(err);
});
server.listen(env.PORT);
console.log("Server started # " + env.IP + ":" + env.PORT);
After trying to run, I received the followings on the console:
Running Node Process
Your code is running at 'http://modified.address.c9.io'.
Important: use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts!
info: socket.io started
Server started # modified.ip.address.1:8080
[Error: Auth error: undefined]
I tried establishing the connection, and it connects to the IP and PORT perfectly. However, the error [Error: Auth error: undefined] appears and stops there. I Googled the error, the supports from the IDE I used..., and surprisingly, there are only 7 links to my problems. So I think it may be a hole in my knowledge or it is not really a problem yet a thing I don't know to work it out. All I could pull out from those Google results were (I was not sure) I need to use client.auth(pass) right after creating it. But where should I find the password? When I installed it npm install redis I didn't configure anything and wasn't told to set password whatsoever. So I reach the impasse.
I use Cloud9 IDE (c9.io), and the modules used as shown in the code above.
----With best regards,
----Tim.
I've found out what was wrong.
I did install Redis, but that is a Redis library that acts like a bridge between Redis driver and NodeJS. On Cloud9, I have to manually install Redis, too.
So it would take 2 commands to actually install Redis:
Install the Redis Driver on Cloud9
nada-nix install redis
Install Redis library for NodeJS
npm install redis
Thanks for anyone who was trying to help me.
You can run the redis-server using your own config file.You can create your own config like below.
//port and ip of ur redis server
port 6371
bind 127.0.0.1
//password for this server
requirepass ucanmentionurpwd
//storing snapshots of the data
save 60 1
dbfilename dump.rdb
dir /tmp/db
//starting redis server
redis-server //ur config file location
See this link for redis configuration
https://raw.github.com/antirez/redis/2.6/redis.conf
If you mention requirepass with your password means only you need to do
client.auth('urPwd');
Otherwise no need to call the client.auth method.

Resources