MongoDB Cloud9 Connection - javascript

So, I am wondering if there is a way to connect to the mongoDB I have setup in my Cloud9 from an html. I mean, I have already connected to the db from the terminal and everything is working like a charm but I need to do some stuff inside my script in an html document and when I try calling the function which contains this code it does nothing
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/ingesoft', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
I have saved the same code into a "file.js" and ran it from console using node file.js and it outputs into the console log "successfully connected to the database", plus the terminal which is running mongo's connection shows me one more connection to the db. The thing is, when I try to run that code inside my script it doesn't work. Sorry for my ignorance I am new to mongo.
Any help would be much appreciated

To simplify your question, here's what's going on:
node file.js containing the code in your question is working
pasting the same code to your html file is not
So, getting to the bottom of the issue, let's ask first: what's the difference between running node file.js and putting the code in html?
The difference is that node ... is running on your Cloud9 workspace (let's call it the server machine).
Your MongoDB server is also running on that server machine
The mongodb npm package you installed is also present on the server machine
The url: mongodb://127.0.0.1:27017/ingesoft references 127.0.0.1 which is the localhost for your server
whereas with the code on your browser:
The code is being run on your customer's machine
That machine doesn't have your Mongodb server
Browser's usually don't support require
You can do requires if you bundle code and use something like webpack or browserify. Did you perhaps do that?
If you did indeed package everything, was the mongodb package that you're requiring packaged?
Can the mongodb package be run from the client side?
The url: mongodb://127.0.0.1:27017/ingesoft references 127.0.0.1 which is the localhost for your customer's machine
Basically, as you can see from the above, the two are very different.
If you want to talk to your db, a lot of people go the following route:
Make a server application that implements some form of REST API
That REST API talks to your DB
Your client code knows how to talk to the REST API and get the required data
That way, you only talk to your MongoDB using your server, and the client can talk to your server via the internet.
This is, of course, an oversimplification, but I hope this resolves your confusion.

Related

How to connect a frontend application on a different port with a backend?

I put my frontend application in the public folder for a node.js application and am getting the form-data using the following request:
try {
await axios.post("/api/v1/contact-form", {
name,
email,
msg,
});
}
My backend is in port 5000 and it's handling the request by:
app.use("/api/v1/contact-form", submitFormRouter);
It works perfect. I'm getting the data when I have my frontend application is in the node.js public folder.
My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I replace the following path for post:
Frontend:
try {
await axios.post("/api/v1/contact-form", {
name,
email,
msg,
});
}
Backend:
app.use("/api/v1/contact-form", submitFormRouter)
I've also tried the code using React in which case the frontend is running in http://localhost:3000/ and node.js server running in 5000, the code still works and I'm getting the form data. But, how do I make it work for a frontend application sitting in a different port(without react)?
Additionally, I hope you're kind enough to answer the following question- What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?
What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?
Let's assume your Back on Heroku has this url https://app.herokuapp.com/ and the Front on Netlify this one https://app.netlify.com/. All you have to do is to give your Front your Back's url, like so:
try {
await axios.post("https://app.herokuapp.com/api/v1/contact-form", {
name,
email,
msg,
});
}
My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I...
At this point you have two choices, the simplest one is to use a complete url like above. Let's assume your Front is on port 3000 and the Back on 8080. All you have to do again is:
try {
await axios.post("http://localhost:8080/api/v1/contact-form", {
name,
email,
msg,
});
}
The second one is to use a proxy, and this really depends on your projects' structure and need.

Pointing socket.io client to heroku service

I have used socket.io, Node.JS, and express to create a real-time chat application that I could view by creating a local server. However, instead of using a local server, I would like to point my client to an existent heroku service. How do I go about doing this?
When I do the following,
var spot = io("https://spotim-demo-chat-server.herokuapp.com");
all functions relating to connecting, disconnecting, username registration, and messaging seem to fail. They do not function in the chat nor do their console.log messages appear in terminal.
I have also considered creating a HTTP server and having it listen to the port and IP address of the heroku service with .listen(). However for my assignment, I was not provided with either of these values, simply the heroku url.
I'm not sure where you're having trouble without more code from you. I've setup a basic socket.io client as follows and can connect without issue. You can run it with the following to see just the client's messages DEBUG=spot-client node client.js or if you wish to see all the debug info from the socket client itself as well DEBUG=* node client.js. The latter might help you diagnose the issue further. Also be sure to install the socket.io-client and debug packages. Hope this helps!
const io = require('socket.io-client');
const debug = require('debug')('spot-client');
var spot = io("https://spotim-demo-chat-server.herokuapp.com");
spot.on('connect', function(){
debug("connected");
});
spot.on('event', function(data){
debug("event",data);
});
spot.on('disconnect', function(){
debug("disconnect");
});

Point mongoos.connect at localhost mongodb

I am studying the MEAN stack by using this tutorial. But the tutorial connects to a remote mongodb installation. I have MongoDB running in the CentOS7 localhost.
How do I alter the mongoose connect line in server.js from the tutorial link above to connect to a localhost database instead of a remote database?
Here is the current line from server.js that needs to be changed to point to the localhost mongodb:
mongoose.connect('mongodb://node:nodeuser#mongo.onmodulus.net:27017/uwO3mypu');
A specific mongodb database has not been created yet. Do I need to create that also?
I'm fairly new at Mongo to, but I know how to connect to a local db. Basically I had to do the following:
Download the latest version of mongodb from https://www.mongodb.com/download-center?jmp=nav#community (according to your settings)
Once installed, I've created a folder that will be containing my DB.
Use a command line instance to start mongo like this:
mongod --dbpath [YOUR_DB_PATH]
Created a DB use mydb
With that you should have already a mongodb db instance looking for connections on default port. So you can change that line for this:
mongoose.connect('mongodb://localhost:27017/mydb');
Again, this is really basic and it is creating a mongo DB connection with all default options. So this will keep you rolling, but you may need to dig a bit more for custom options.
Hope this helps

Node.js not closing files created by fs.createReadStream()

On my server, every time a user uses our service we have to grab a JSON file for them from the server. I do this by using fs.createReadStream() inside of my own function.
function getJSONFromServer(filepath, callback){
var data = fs.createReadStream(filepath);
data.on('error', function (error) {
console.log("Caught", error);
callback(undefined, error);
});
var jsonFile = "";
data.on('data', function(chunk) {
jsonFile += chunk;
});
data.on('end', function() {
var jsonData = JSON.parse(jsonFile);
callback(jsonData);
data.destroy();
data.close();
});
}
This does the job, but it does not close the connection to the file. So after reading 1024 files (the limit on my server), Node.js will then produce the error EMFILE, too many open files. Then I have to kill our Node.js server, open it again and that will clear the "open files".
I check the amount of files open by lsof -i -n -P | grep nodejs. It displays something like this:
nodejs 13707 node 10u IPv4 1163695 0t0 TCP 127.0.0.1:55643->127.0.0.1:27017 (ESTABLISHED)
nodejs 13707 node 11u IPv4 1163697 0t0 TCP 127.0.0.1:55644->127.0.0.1:27017 (ESTABLISHED)
for as many files that are open.
I've tried using graceful-fs. I've tried calling stream.destroy() and stream.close(), but I still get the same issue. My server is essentially a ticking time bomb because we get a heavy, steady flow of users and after so many users have connected it will just stop working.
Also, ulimit -n [open file amount] does not work, and even if it did, this is not a long term solution because I'd like my file connections to close and not sit open for no reason.
I'm using Node.js version v0.10.25, Ubuntu 15.04 (GNU/Linux 3.19.0-42-generic x86_64) and the latest version of graceful-fs if that helps!
Thanks for any help you can provide.
This has got to be the stupidest mistake I've ever made. Regardless, here's the answer. I hope I can save someone from dealing with this error and almost ripping their hair out.
I was running my app with nodejs and not node. Turns out, if you do nodejs --version, it will likely return a version that is very old, which was v0.10.25 for me. node --version however was v5.6.0. Obviously this massive jump in versions would fix some stuff, so I ran the app with node app.js instead of nodejs app.js and I haven't had the issue at all since. There are now only 6 open files, whereas before we had over 1000 with time.
Damn it feels good to have this off my chest.

how to run node.js on windows with apache server installed in?

I'm a node.js begginer . Let's say I have an apache server(XAAMP) and node.js installed in C:\Program Files\nodejs\nodejs.exe on windows 7.
How can I run node.js in my apache server to simulate my code?
I mean, I know how to write node.js code but what I don't know how it's work on my server?
Apache server don't need for Node.js.
For create your own Node.js server:
Download and install Node.js
Create file hello.js:
var http = require("http");
var server = http.createServer().listen(3000); // beter way for create
server.on("request", function(req, res){
res.writeHead(200, {"Content-Type": "text/plain"});
// for view at page http://localhost:3000
res.write("Hello world");
res.end();
});
server.on("listening", function(){
// for view in console
console.log("Listen: 3000...");
});
In terminal go to dir where file hello.js and type:
node hello.js
Open your browser and point it at http://localhost:3000/. This should display a web page that says:
Hello world
A basic HTTP server
Node.js Manual & Documentation
If you like to work with a replacement for XAAMP you should finally take a look at MEAN.io.
At NpmJS.org you will find different solutions for most of your needs.
and like Reagan Gallant commented you should take a look at this famous stackoverflow post (if you need ideas).
NodeSchool indeed is a good entry point for your fist steps. After that npmjs will make sense and finally you will love Mean.io
You just make it use a different port than Apache is using (for example port 3000 which is the default for express-js and others) -- that is assuming that you don't need the two to work together.
If you do need them to work together, you add a forwarding module to Apache and configure the forwarding in Apache of certain URL to go to your local port for node-js

Categories

Resources