in my index.js file:
const express = require('express');
const router = express.Router();
// Do work here
router.get('/', (req, res) => {
res.send('Hey! It works!');
});
module.exports = router;
I am able to make the first request just fine, but every subsequent request just waits for localhost until it times out.
app.js looks like:
const express = require('express');
const session = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const passport = require('passport');
const promisify = require('es6-promisify');
const flash = require('connect-flash');
const expressValidator = require('express-validator');
const routes = require('./routes/index');
const helpers = require('./helpers');
const errorHandlers = require('./handlers/errorHandlers');
// create our Express app
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views')); // this is the folder where we keep our pug files
app.set('view engine', 'pug'); // we use the engine pug, mustache or EJS work great too
// serves up static files from the public folder. Anything in public/ will just be served up as the file it is
app.use(express.static(path.join(__dirname, 'public')));
// done! we export it so we can start the site in start.js
module.exports = app;
the start.js file looks like this. I should add that this is not my own code - it's part of the node.js tutorial from Wes Bos.
const mongoose = require('mongoose');
// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });
// Connect to our Database and handle any bad connections
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
console.error(`🙅 🚫 🙅 🚫 🙅 🚫 🙅 🚫 → ${err.message}`);
});
// READY?! Let's go!
// Start our app!
const app = require('./app');
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
Managed to solve my own problem, so I'm reporting back for anyone who may have encountered the same issue coming from the Wes Bos Node.js tutorial.
The solution was to double check my variables.env file - I had stupidly left arrow brackets around the username and password fields. If you're having this issue, make sure your DATABASE environment variable looks something like this:
DATABASE=mongodb://dang:dang#ds057833.mlab.com:57833/dang-thats-delicious
Related
I am working on Node Js and I am facing issue in my routes.js file and app.js file.
Routes file is no working.
App.js code
const express = require('express');
const app = express();
const routes = express.Router('./routes/routes');
const path = require('path');
const methodOverride = require('method-override');
const moment= require('moment');
app.locals.moment=moment;
app.locals.shortDateFormat="MM/DD/YYYY";
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'index.jade'));
Route.js code
var express=require('express');
var routes= express.Router();
var controllers= require('../controllers');
// homepage routes
routes.get('/',controllers.homeController.index);
You need to export the routes from Route.js file
var express=require('express');
var routes= express.Router();
var controllers= require('../controllers');
// homepage routes
routes.get('/',controllers.homeController.index);
module.exports = routes
and in app.js
app.use('/', routes)
I'm connecting to MongoDB from my Node.js.
If I start my connection from app.js file, then do I need to connect again from another JavaScript file, for example: from one of my models folder?
Here's my code for database.js:
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
const mongoConnect = callback => {
MongoClient
.connect("mongodb+srv://<user>:<password>#node.idgpt.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", {useUnifiedTopology: true})
.then(client => {
console.log("CONNECTED!!!");
callback(client);
})
.catch(err => {
console.log(err);
});
}
module.exports = mongoConnect;
Here's my code of app.js:
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const errorController = require('./controllers/error');
const mongoConnect = require('./util/database');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminRoutes = require('./routes/admin');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
mongoConnect(() => {
app.listen(3000);
});
So, my question is: Do I need to connect to MongoDB through mongoConnect function every time I want to perform CRUD operation? For example: if I want to insert data from another file which is in models folder, do I need to connect to MongoDB first and then execute the insert operation, because I already first connect to MongoDB from my app.js and then I start listening to my node server.
Note: I have replaced my username and password with <user> and <password> respectively.
provide sample code for more insights.
but if you connect in one file you can require this file in many files, it will always be the same connection.
I am new in node js and want to build an application in which they are multiple APIs and all are settled in routes folder but here is the problem when I tried to call the API in index.js(main file) its only take one route either userAPI or cleanerAPI.
As both APIs have different URL.
var mongoose = require ('mongoose');
var express = require('express');
const bodyParser = require('body-parser');
var app = express();
const routerUser= require('./routes/userAPI')
mongoose.connect('mongodb://localhost:27017/Covid');
app.use(bodyParser.json());
app.use('/',router);
app.listen(4000,function(){
console.log("Server Running on 4000")
});
you can try this one also.
Main file(index.js or server.js)
const appRoutes = require('./Routes')
appRoutes(app)
Routes(index.js)
module.exports = app => {
app.use("/user", require('./users'));
app.use("/cleaner", require('./cleaner')); };
Routes(users.js)
const express = require('express');
const router = express.Router();
router.route('/list')
.post(function(req,res){......});
module.exports = router;
I started learning database with MongoDB and Node.js not long ago and I'm trying to find a way to use Express routes without mongoose. I want to insert data using Express routes and have clean code exporting different modules. The problem is that i can't write routes
as below because in my index.js file "db" is of course not defined and apparently i can't insert data into my "db" outside of the function "client.connect" as with mongoose. Do i have to connect my db in a file with all my posts or is there a specific way to do it? (sorry for my English, I'm learning it).
App.js :
const express = require('express');
const app = express();
const expressLayouts = require('express-ejs-layouts');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
//EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
//Styles
app.use('/public', express.static('public'));
//Bodyparser
app.use(express.urlencoded({extended: false}));
//Connect to DB
const url = 'mongodb://localhost:27017/shopping'
const dbName = 'shopping';
const client = new MongoClient(url);
client.connect((err)=>{
assert.equal(null, err);
console.log('connected to db...');
app.use('/', require('./routes/index'));
const db = client.db(dbName);
});
//Server
app.listen(3000, ()=>{console.log("Listening to port 3000")});
index.js (routes):
const express = require('express');
const router = express.Router();
//Get home page
router.get('/', (req, res)=>{
res.render('shop/index')
});
router.get('/posts', (req,res)=>{
res.render('posts')
});
router.post('/posts',(req,res)=>{
db.collection('users').insertOne({'name': req.name, 'password': req.password});
});
module.exports = router;
Index.js should include a function with which to pass your mongo client in. So for example:
let mongoClient
router.passMongoClient = function(clientIn){
mongoClient = clientIn
}
Then after you've started your client, pass it in through your new function
const router = require(./router)
client.connect((err)=>{
assert.equal(null, err);
console.log('connected to db...');
app.use('/', require('./routes/index'));
const db = client.db(dbName);
router.passMongoClient(db)
});
This is the basic idea. You may wish to structure your code a little differently. I wait to start my http server until I get the callback from the mongodb client that it's connected. Depends on your use case to a degree.
I have created a folder testint
My testint/app.js having following code
const express = require('express'); const path = require('path');
const bodyParser = require('body-parser'); const cors = require('cors');
const passport = require('passport'); const mongoose = require('mongoose');
const app = express(); const port = 7000; app.use(cors());
app.use(bodyParser.json());
app.use('/users', users); //Not working
app.get('/',(req,res) => {
res.send("Invalid Endpoint");
});
app.listen(port, () =>{
console.log('Server started on port '+ port);
});
testint/routes/users.js contains :
const express = require('express'); const router = express.Router();
res.send('Authenticate');
router.get('/register',(req, res, next) => {
res.send('REGISTER');
});
module.exports = router;
If I run http://localhost:7000/users/register
Am getting :
Cannot GET /users/register
I dint know where am wrong and am new to node any help will be appreciated.
I got solution. I didn't include
const users = require('./routes/users');
in app.js
and res.send('Authenticate'); in users.js is not required for instance.