react + mongodb port - javascript

I'm trying to build react app with mongoDB. React app is running on port 3000
and when i'm running server.js for mongodb on the same port, my app is overriten.
How do I make mongoDB to run on same port?
Thanks

You can't run the web server and database on the same port. The convention is to use the next port, ie 3001 for Mongo.
It doesn't actually matter which port Mongo runs on, as long as your app knows about it
UPDATE
Run mongo with a command like this:
mongod --dbpath=/home/me/mydata --port 3001
If you are using npm package mongodb, connect like this
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:3001/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});

Related

MongooseServerSelectionError: connect ETIMEDOUT

I recently ran into this problem. When I try to run my Node.js app, I get this error MongooseServerSelectionError: connect ETIMEDOUT. It also said type: 'ReplicaSetNoPrimary'. For the past few months it was working perfectly and I had never got this error. I am using MongoDB Atlas for the database and Mongoose for its driver. I am using the latest version of Mongoose.
Here is my app.ts:
const CONNECTION_URL = "mongodb+srv://name:<password>#cluster0.vyegx.mongodb.net/MyApp?retryWrites=true&w=majority"
mongoose.connect(CONNECTION_URL).then(_INIT_)
async function _INIT_(){
const server = app.listen(PORT, ()=>{
console.log("listening on port "+PORT+"...")
});
const io = new Server(server);
}
I have tried to whitelist my ip, but it's not working.
UPDATE It works perfectly with no errors in Heroku but when I try to run it from my computer it gives an error.
need to set useUnifiedTopology: false

How to structure docker container ports? Use --net or --link?

I have 2 docker containers. One contains a simple node.js web app which contains server information and MongoDB connection details. The second contains a running instance of MongoDB.
I am attempting to run the web app container to connect to the MongoDB container like so:
docker run --link mongodb2:mongodb2 -p 49160:8080 -it --name web node-web-app
Doing this I can successfully access and view the hosted page at http://hostname:49160/ but I cannot connect to MongoDB.
Another method I have tried is:
docker run --net container:mongodb2 -ti --name web node-web-app
Here I can successfully connect to MongoDB, but I cannot access my hosted page at http://hostname:27017/. Instead I receive the message:
It looks like you are trying to access MongoDB over HTTP on the native driver port.
I have also attempted to pass port details like so using the --net method:
docker run --net container:mongodb2 -p 49160:8080 -ti --name web node-web-app
but I receive a docker error:
docker: Error response from daemon: conflicting options: port publishing and the container type network mode.
See 'docker run --help'.
I believe there is an issue with the way I am configuring my ports, but I am new to both docker and setting up web servers.
Here is my web app code:
'use strict';
const express = require('express');
// App
const app = express();
// Constants
const PORT = 8080;
const HOST = '0.0.0.0';
const MongoClient = require('mongodb').MongoClient;
// Connect URL
const url = 'mongodb://127.0.0.1:27017';
var db;
var ticket;
MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
if (err) {
return console.log(err);
}
// Specify database you want to access
db = client.db('DB');
console.log(`MongoDB Connected: ${url}`);
ticket = db.collection('ticket');
ticket.find().toArray((err, results) => {
console.log(results);
});
});
//Routes
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
});
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`)
You should use a named Docker network to connect between containers. Once you do, the other containers' names will be usable as host names.
docker network create some-network
docker run -d --net some-network --name mongodb2 mongo
docker run -d --net some-network --name app -p 49160:8080 node-web-app
In your source code, you can't hard-code the location of the database, since it's somewhat likely it won't be on the same machine or in the same container when you deploy it. localhost could be a reasonable developer default but the option needs to be configurable.
const mongoHost = process.env.MONGO_HOST || 'localhost';
const url = `mongodb://${mongoHost}:27017`;
docker run ... -e MONGO_HOST=mongodb2 ...
If you're using Docker Compose to launch things, it provides a default network for you (different from the "default bridge network" in the core Docker documentation) and you need to do very little setup; just use the other container's Compose service name as a host name.
version: '3.8'
services:
mongodb2:
image: mongo
app:
build: .
ports: ['49160:8080']
environment:
- MONGO_HOST=mongodb2
Of the other options you propose, --link is considered obsolete now that named networks have essentially replaced it. Setting one container to run in another's network namespace is also a very unusual setup, and it comes with limitations like what you show.

How to determine if Express app's connection to MongoDB is really open?

I'm working on an Angular 7 app with MongoDB, Node and Express. If I start my Express app (using npm start command) before connecting to MongoDB (with mongod command), the Express app first throws an error because it's unable to establish connection with MongoDB. Once MongoDB is up and running, the Express app informs me that MongoDB is now connected at port 27017. However, any http post requests I execute through my Angular app cause Express to return a 200 status code (which tells me everything is ok), but MongoDB fails to create a document as a result of the http post request. How do I make sure that MongoDB is not only connected but that the connection can successfully create the new document when I execute the post http request? I read somewhere that MongoDB's ability to save/create a document requires it to have an open connection. In that regard, what's the difference between having an open connection and MongoDB being connected at port 27017?
Here's the code I use in my Express app.js file to connect to MongoDB:
var express = require('express');
var mongoose = require('mongoose');
var app = express();
var mongoose_uri = process.env.MONGOOSE_URI || "mongodb://abc:abc123#localhost:27017/databank?authSource=admin";
mongoose.set('debug', true);
mongoose.connect(mongoose_uri);
mongoose.connection.on('connected', ()=>{
console.log('MongoDB connected at port 27017');
});
//Not sure if the mongoose.connection.once is necessary to have, considering I already have mongoose.connection.on above.
mongoose.connection.once('open', ()=>{
console.log('MongoDB connection now open');
})
//MongoDB connection error
mongoose.connection.on('error', (err)=>{
console.log(err);
})
Here's the npm log, showing the connection error at first, followed by successful connection, followed by several Post requests with status code 200, yet nothing got saved to the MongoDB collection.
[nodemon] 1.19.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
API Gateway listening at http://localhost:8085/api
Web Server listening at http://localhost:8085/
{ Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
name: 'MongoError',
message: 'connect ECONNREFUSED 127.0.0.1:27017' }
MongoDB connected at port 27017
POST /api/contactus 200 335.509 ms - 18
POST /api/contactus 200 9.082 ms - 18
POST /api/contactus 200 3.916 ms - 18
POST /api/contactus 200 6.268 ms - 18
POST /api/contactus 200 61.876 ms - 18
Of course, this problem was resolved when I restarted my express app after an active mongoDB session, but I won't always have the luxury of inspecting logs and the app's ability to create documents when in production. Appreciate some guidance.
You have to connect to mongo first, then initialize express.
mongoose.connection.on('connected', ()=>{
console.log('MongoDB connected at port 27017');
app = express();
});
//once open event is not necessary
After that, you can consider writing init functions that all return promises. Like that you can chain it and all is clear. Here is an example where rabbit, then mongo, then express is inited.
initRabbit()
.then(initMongo)
.then(initExpress)
.catch(e => {
error({error:"boot", cause: e})
process.exit(-1)
})
const initMongo = () => new Promise(resolve => mongoose.connection.on('connected', resolve))

Nodejs - Connecting to mongodb database within a js file?

So i have been looking at how to use mongodb from this tutorial: http://doduck.com/node-js-mongodb-hello-world-example/
I have installed mongodb locally within my project folder that contains my html css and js, i run npm list mongodb within the project folder and i get the mongodb version. I haven't installed it globablly, but as far as i know that is ok right?
Anyways, i tried adding the example from the tutorial to test connect to a mongodb database. I just created a function and called it as soon as my page loads:
function connectMongo(){
alert("test1");
var MongoClient = require('mongodb').MongoClient;
alert("test2");
var myCollection;
var db = MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err){
throw err;
alert("mongoerror");
}
alert("connected to the mongoDB !");
// myCollection = db.collection('test_collection');
});
}
The first test alert works, but the second test does not appear. However, the rest of the code on the page still runs, so i dont think there is a syntax error. I have no idea how exactly im meant to run this example, can anyone tell me why my function is exiting after the line
var MongoClient = require('mongodb').MongoClient;
I also have mongoose installed, even though im not quite sure if im even using it in my example here
Sorry if my question is kind of vague, i have honestly no idea what im doing here
First although Nodejs is written in Javascript, you must clearly distinguish between client and server functions. Javascript's alert() is useful to pop messages on your browser. This is isn't something Nodejs does as it is a server app.
Forget about alert("message"); You want to use console.log("message"); to view log info on the server console.
Prerequisite
Let's quickly review Client-Server web interactions:
Server is up and running
Client Requests page via browser
Page shows up on the client's browser
Step 1
The missing step for you is (1), because the server is not up and running.
This is done by typing the following on your terminal:
$ node name_of_file_here.js
If there are errors in your syntax, or missing dependencies the console will log the errors. If none appear all should be well.
Step 2
Now at this point, you still can't expect to see anything "relevant" on the browser, because your server although it has setup a MongoDB instance, is still not listening to requests from clients.
Some code needs to be added:
'use strict';
var http = require('http');
var PORT=8009;
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
var d = MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
//Create a server
var server = http.createServer(function(request, response) {
console.log("received request");
// use MongoClient to get relevant data
// var relevant_data = ...;
// response.write(relevant_data);
response.write("hey there");
response.end();
});
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
Final Note
I am in no way a MongoDB guru, but I believe a mongodb service (server) has to be running on your system for the MongoDB client to be able to create a connection.
It sounds like you are trying to run the mongo connection javascript in the browser. The mongodb connection runs on the server via the node executable. So this is javascript code in the web app running server side, rather than javascript delivered by the web app to a browser to run client side.
Create a file test.js
function connectMongo(){
var MongoClient = require('mongodb').MongoClient;
console.log('MongoClient is',typeof MongoClient)
var myCollection;
var url = 'mongodb://127.0.0.1:27017/test';
var db = MongoClient.connect(url, function(err, db) {
if(err){
console.log("mongoerror", err);
throw err;
}
console.log("connected to the mongoDB!");
myCollection = db.collection('test_collection');
});
}
connectMongo()
Then on your system, at a command or shell prompt, run
node test.js
It should print
$ node test.js
MongoClient is function
connected to the mongoDB!
^C
Once your server is connected to the database you can pass messages from your front end javascript to the backend server code. Normally this is done via an Ajax http request, so your javascript makes additional HTTP requests in the background. The JQuery client side library provides a simple cross browser API for this. You could also use Websockets to pass message back and forth from the server via SocketIO
For the basics of a Node/Express/MongoDB app try this: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

Socket.io-client simple client/server test wont connect - Node.js

I am trying to get some simple communication to work in Node.js using socket.io and socket.io-client.
I have two scripts, server.js and client.js.
The server.js script can bind to a webfacing port and act like a normal server/socket.io host, which all works when used with the browser client,
but the client.js (running in another node script) doesn't work, it just waits not outputting anything. I expect my socket.io-client in client.js to connect to the socket.io instance in server.js and for both to display a message in their console to say they're connected.
server.js code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
console.log("\nNew server request: "+req.url+"\n");
// sends a html file with a script that connects
// to socket.io running in server.js
res.sendFile(__dirname+'/webroot/index.html');
});
// listens for connections
io.on('connect', function(socket){
console.log('a client connected');
});
// start listening on server
http.listen(9000, function(){
console.log('listening: 9000');
});
client.js code:
var io = require('socket.io-client');
// connect to server.js socket
var socket = io('http://hostsite.com', {
port: 9000
});
socket.on('connect', function(){
console.log("connected\n");
});
installed with npm
npm install socket.io // version: 1.0.6
npm install socket.io-client // version: 1.0.6
npm install express // version: 4.8.5
Ideally I don't want to be using express or an http server, just a socket communication between two Node.js scripts, one on a server machine, one on a client machine.
Thanks for any help :)
For some reason, it wouldn't connect when i used:
npm install socket.io-client
and
require('socket.io-client');
But it does connect if I use the client that comes with the main package
npm install socket.io
and
require('socket.io/node_modules/socket.io-client');
Took a while to figure out, but hopefully now it will take someone else less time; if they face the same problem.
have you tried:
var socket = io.connect('http://hostsite.com:9000');

Categories

Resources