I am trying to create a very simple website. I have created a basic database on mLab and have setup a user with dbuser = folr and dbpassword = folr. However when trying to connect I get the error message:
{ [MongoError: connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONNREFUSED' }
Why is this happening?
const express = require('express')
const app = express()
const bodyParser= require('body-parser')
const MongoClient = require('mongodb').MongoClient
var db
MongoClient.connect('mongodb://folr:folr#ds047712.mlab.com:47712/familytimeline', function(err, database) {
if (err) return console.log(err)
db = database
app.listen(process.env.PORT || 3000, function() {
console.log('listening on 3000')
})
})
app.use(bodyParser.urlencoded({extended: true}))
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
app.post('/new', function(req, res) {
db.collection('quotes').save(req.body, function(err, result) {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
})
})
Related
I'm a beginner and try to create a rest API following this tutorial. I expected to see Server is running on port: ${PORT}, but it seems like my code can't reach it. I got no error on my terminal and it looks like this
Here are my code:
server.js
require('dotenv').config({ path: './config.env' });
const express = require('express');
const cors = require('cors');
const dbo = require('./db/conn');
const PORT = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./api/api'));
// Global error handling
app.use(function (err, _req, res) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// perform a database connection when the server starts
dbo.connectToServer(function (err) {
if (err) {
console.error(err);
process.exit();
}
// start the Express server
app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});
});
conn.js
const MongoClient = require('mongodb').MongoClient
const dotenv = require("dotenv")
dotenv.config()
const connectionString = process.env.MONGOURI
let db;
module.exports = {
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) return console.error(err)
db = client.db('db-name');
console.log('Connected to Database');
return callback
});
},
getDb: function () {
return db;
}
}
api.js
const express = require("express");
const gameRoutes = express.Router();
const dbo = require('../db/conn');
gameRoutes.route("/game").get(async function (_req, res) {
const dbConnect = dbo.getDb();
dbConnect
.collection("game")
.find({}).limit(50)
.toArray(function(err, result) {
if (err) {
res.status(400).send("Error fetching listings!");
} else {
res.json(result);
}
})
})
module.exports = gameRoutes;
Can you please tell me what's wrong with my code? I really can't find why the server is not running. Thanks in advance! I'll be very grateful for your help!
In your connectToServer method you just returning the callback. But you actually need to call it as well.
So change this
return callback
to this
return callback(null);
If you want to pass the possible error from MongoClient to the callback as well, then change your connectToServer method to this :
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) { return callback(err); }
db = client.db('db-name');
console.log('Connected to Database');
return callback(null) // no error, so pass "null"
});
}
I developed a bug tracker app using MERN, and on local, the interface updates in real time when the user performs CRUD operations using react hooks (state) and react context.
But once I deployed my app on google cloud, it seemed to turn into a static website, and if I add,edit, or delete, I have to refresh the page to see the change.
What could be causing this to happen?
Here is my server.js code:
require("dotenv").config();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const ticketRoutes = express.Router();
const PORT = 8080;
var path = require("path");
let Ticket = require("./ticket.model");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGO_DB, { useNewUrlParser: true, useUnifiedTopology: true }, (error) => {
console.log(error);
});
const connection = mongoose.connection;
connection.once("open", function () {
console.log("MongoDB database connection established successfully");
});
ticketRoutes.route("/").get(function (req, res) {
Ticket.find(function (err, tickets) {
if (err) {
console.log(err);
} else {
res.json(tickets);
}
});
});
ticketRoutes.route("/:id").get(function (req, res) {
let id = req.params.id;
Ticket.findById(id, function (err, ticket) {
res.json(ticket);
});
});
ticketRoutes.route("/add").post(function (req, res) {
let ticket = new Ticket(req.body);
ticket
.save()
.then((ticket) => {
res.status(200).json({ ticket });
})
.catch((err) => {
res.status(400).send("adding new ticket failed");
});
});
ticketRoutes.route("/delete/:id").delete(function (req, res) {
Ticket.findByIdAndRemove(req.params.id, function (err, ticket) {
if (err) {
console.log(err);
return res.status(500).send({ ticket });
}
return res.status(200).send({ ticket });
});
});
ticketRoutes.route("/update/:id").post(function (req, res) {
Ticket.findById(req.params.id, function (err, ticket) {
if (!ticket) res.status(404).send("data is not found");
else ticket.ticket_name = req.body.ticket_name;
ticket.ticket_status = req.body.ticket_status;
ticket
.save()
.then((ticket) => {
res.json({ ticket });
})
.catch((err) => {
res.status(400).send("Update not possible");
});
});
});
app.use("/tickets", ticketRoutes);
app.use(express.static(path.join(__dirname, "frontend/build")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "frontend/build/index.html"));
});
app.listen(process.env.port || 8080, () => {
console.log("Express app is running on port 8080");
});
The fix was very in depth, but basically my method of deployment to google cloud was a method that would only work with static web pages. I ended up deploying the app with heroku using this great guide: enter link description here
I just started with backend and I am tying to deploy backend of my crud app but I am getting stuck for routes. After deploying on heroku I just get the part of app.get('/'). I can't find any router.get('/getData'.. or router.post('/updateData'..
here is the deployed heroku link:
for app.get('/'): https://vast-beyond-50574.herokuapp.com/
for router.get('/getData): https://vast-beyond-50574.herokuapp.com/getData
for router.post('/updateData'): https://vast-beyond-50574.herokuapp.com/updateData
Here is the code for backend server.js
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const Data = require('./data');
const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/backend');
let db = mongoose.connection;
db.once('open', () => console.log('connected to the database'));
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev'));
router.get('/getData', (req, res) => {
Data.find((err, data) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
});
});
router.post('/updateData', (req, res) => {
const { id, update } = req.body;
Data.findByIdAndUpdate(id, update, (err) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
router.delete('/deleteData', (req, res) => {
const { id } = req.body;
Data.findByIdAndRemove(id, (err) => {
if (err) return res.send(err);
return res.json({ success: true });
});
});
router.post('/putData', (req, res) => {
let data = new Data();
const { id, message } = req.body;
if ((!id && id !== 0) || !message) {
return res.json({
success: false,
error: 'INVALID INPUTS',
});
}
data.message = message;
data.id = id;
data.save((err) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
app.get('/', (req, res) => {
res.send('Deployed!');
});
app.use('/api', router);
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log(`LISTENING ON PORT ${PORT}`));```
You're using your router inside the /api route (app.use('/api', router);) which means all of those routes will be prefixed with /api. So, you should be able to visit https://vast-beyond-50574.herokuapp.com/api/getData and see your data. (However, I tried this and got a different error, which you will have to debug separately).
I'm new at using back-end code.
I'm trying to Insert basic line into MongoDB online DB.
These are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
var db = require('./config/db');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err);
db = database.db('note-api');
require('./app/routes')(app, db);
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
note_routes.js:
module.exports = function (app, db) {
// const collection =
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': err });
} else {
res.send(result.ops[0]);
}
});
});
};
db.js:
module.exports = {
url: "mongodb://laelav:laelav1#ds227594.mlab.com:27594/getremp"
};
Whenever i try using POST and wish to update the online DB - I get an unauthorized error:
unauthorized error
Then I added this line in note_routes.js:
db.grantRolesToUser("laelav", [{ role: "readWrite", db: "getremp" }]);
And got the following "TypeError: db.grantRolesToUser is not a function":
not a function error
Please help!
Hi I am new to backend node applications and I am trying to create a clean API driven node.js app without frameworks by working with scripts and pug template engine.
I have created a serve.js file with all the necessary code:
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
const bodyParser = require("body-parser");
var mongodb = require("mongodb");
const MongoClient = require('mongodb').MongoClient
var ObjectID = mongodb.ObjectID;
var indexRoutes = require('./routes/index');
var thePort = process.env.PORT || 5000;
var SECTIONS_COLLECTION = "sections";
//make results available as json
app.use(bodyParser.json());
//External database identifier
var db;
//Path to the database with URI
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2orjhen7knanjpfmd7#ds014586.mlab.com:19986/heroku_fmvc5nhk';
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(dbpath, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
//static folder directory
app.use(express.static(__dirname + '/dist'));
// Initialize the app.
var server = app.listen(process.env.PORT || thePort, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
//set up routes directory
app.use('/', indexRoutes);
// Views and Template Engine
//app.set('views', __dirname + './views');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// sections API ROUTES:
/* "/api/sections"
* GET: finds all sections
* POST: creates a new contact
*/
app.get("/api/sections", function(req, res) {
db.collection(SECTIONS_COLLECTION).find({}).toArray(function(err, docs) {
if (err) {
handleError(res, err.message, "Failed to get sections.");
} else {
res.status(200).json(docs);
}
});
});
app.post("/api/sections", function(req, res) {
var newContact = req.body;
if (!req.body.name) {
handleError(res, "Invalid user input", "Must provide a name.", 400);
}
db.collection(sections_COLLECTION).insertOne(newContact, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new contact.");
} else {
res.status(201).json(doc.ops[0]);
}
});
});
/* "/api/sections/:id"
* GET: find contact by id
* PUT: update contact by id
* DELETE: deletes contact by id
*/
app.get("/api/sections/:id", function(req, res) {
db.collection(SECTIONS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get contact");
} else {
res.status(200).json(doc);
}
});
});
app.put("/api/sections/:id", function(req, res) {
var updateDoc = req.body;
delete updateDoc._id;
db.collection(SECTIONS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to update contact");
} else {
updateDoc._id = req.params.id;
res.status(200).json(updateDoc);
}
});
});
app.delete("/api/sections/:id", function(req, res) {
db.collection(SECTIONS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
if (err) {
handleError(res, err.message, "Failed to delete contact");
} else {
res.status(200).json(req.params.id);
}
});
});
In my views\about.pug template I reference my JSON object's contents.
//--about.pug
extends index.pug
block div.root
h2= #{about.heading}
h3= #{about.summary}
p #{about.content}
In my routesroutes/index.js I have pre-existing "flat" examples with pug then one dynamic about example:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render(
'index',
{
title: 'Welcome to Awesome Place',
header: 'Home',
summary: 'This is my home. It can\'t be any simpler'
}
)
})
Dynamic example:
//About
router.get('/about', function (req, res) {
//retrieve all home from Mongo
db.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) {
if (err) {
handleError(res, err.message, "Failed to get sections.");
} else {
res.render('about', {})
console.log(result)
}
}
})
The above is returning a db is not defined error.
If var indexRoutes = require('./routes/index'); is required as part of my server.js file, why can't it find the value of db?
UPDATED CODE (TOO MANY ERRORS)
//server.js
//APP Dependences
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var indexRoutes = require('./routes/index');
var bodyParser = require("body-parser");
//PORT
var thePort = process.env.PORT || 5000;
// Views and Template Engine
//app.set('views', __dirname + './views');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//Documents
app.use(bodyParser.json());
//static folder directory
app.use(express.static(__dirname + '/dist'));
//set up routes directory
app.use('/', indexRoutes);
// Catch errors
app.use(function(req, res, next) {
res.status(404).sendFile(process.cwd() + '/app/views/404.htm');
});
// Initialize the app.
var server = app.listen(process.env.PORT || thePort, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
var mongodb = require("mongodb");
const MongoClient = require('mongodb').MongoClient
var ObjectID = mongodb.ObjectID;
var SECTIONS_COLLECTION = "sections";
//External database identifier
var db;
//Path to the database with URI
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2ovanbfd7knanjpfmd7#ds019986.mlab.com:19986/heroku_fmvc5nhk';
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(dbpath, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || thePort, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
//db.js
var express = require('express');
var mongodb = require("mongodb");
var MongoClient = require('mongodb').MongoClient
var ObjectID = mongodb.ObjectID;
var assert = require('assert');
//Path to the database with
var dbpath = process.env.MONGODB_URI || 'mongodb://heroku_fmvc5nhk:5rqdhjqc2ovahen7knanjpfmd7#ds019986.mlab.com:19986/heroku_fmvc5nhk';
//Get the section
var SECTIONS_COLLECTION = "sections";
// Use connect method to connect to the server
var database;
function connectMongo(cb){
MongoClient.connect(dbpath , function(err, database) {
assert.equal(null, err);
console.log("Connected successfully to server");
cb(database);
});
}
module.exports = connectMongo;
//routes/index.js
var express = require('express');
var router = express.Router();
var connectDB = require ('../db')
router.get('/', function (req, res) {
res.render(
'index',
{
title: 'Welcome to Awesome Place',
header: 'Home',
summary: 'This is my home. It can\'t be any simpler'
}
)
})
connectMongo(function(database){
//About
router.get('/about', function (req, res) {
//retrieve all home from Mongo
database.collection(SECTIONS_COLLECTION).find({"name": "about"}), function (err, about) {
if (err) {
handleError(res, err.message, "Failed to get sections.");
} else {
res.render('about', {})
console.log(result)
}
}
})
}
router.get('/work', function (req, res) {
res.render(
'work',
{
title: 'Work, Work, Work , Work...',
header: 'Work life',
summary: 'My first work for this bitch',
imgUrl: '/img/firaz.jpg'
}
)
})
router.get('/contact', function (req, res) {
res.render(
'contact',
{
title: 'Contact Me Any Time',
header: 'Contact Me Any Time',
summary: 'Fill the form below to be contacted'
}
)
})
module.exports = router;
Because db variable is not global by requiring var indexRoutes = require('./routes/index'); you are importing the objects from routes/index file to server not the other way around.
what you can do is make your db variable global global.db and access it anywhere or create a seperate file for mongo db connection and require that in routes file
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/database';
// Use connect method to connect to the server
var database;
function connectMongo(cb){
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
cb(db);
});
}
module.exports = connectMongo;
This github Repo got good structure for mongoDB
https://github.com/OmarElGabry/chat.io