I understand the error but I am just not sure I understand how to properly do what I am trying to do to stay organized.
Error: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners added.
index.js
//define routes
const userRoutes = require("./api/route/user"); //bring in our user routes
app.use('/', userRoutes);
module.exports = userRoutes;
const clientRoutes = require("./api/route/client");
app.use('/', clientRoutes);
module.exports = clientRoutes;
const contractorSkillRoutes = require("./api/route/clientskill");
app.use('/', contractorSkillRoutes);
module.exports = contractorSkillRoutes;
user.js
const express = require("express");
const router = express.Router();
const userController = require("../controller/userController");
const auth = require("../../config/auth");
router.post("/login", userController.loginUser);
router.post("/register", auth, userController.registerNewUser);
router.get("/getusers", auth, userController.getAllUsers);
router.get("/authorize", auth, (req, res) => {res.status(200).json({ authorization: true });});
router.post("/deleteuser", auth, userController.deleteUser);
router.post("/edituser", auth, userController.editUser);
module.exports = router;
client.js
const express = require("express");
const router = express.Router();
const clientController = require("../controller/clientController");
const auth = require("../../config/auth");
router.get("/getallclients", auth, clientController.getAllClients);
router.post("/newclient", auth, clientController.newClient);
router.post("/getclientbyid", auth, clientController.getClientById);
router.post("/editclient", auth, clientController.editClient);
module.exports = router;
You get the idea.
I recognize that I should probably not be using app.use several times but I also just don't get how to include all of the files into one use statement. All of the examples I can find are just including all of the routes in one routes file. Should be a simple fix, I just can't seem to figure it out.
Related
I am new to Node.js. After watching many explanatory videos and and reading the Node.js docs, I started developing the site while respecting an MVC structure. The node server seems to work but the display on the front shows Cannot GET /. Here is the Browser Screenshot and the MVC structure of the project
index.js code :
'use strict';
/* eslint-env node, es6 */
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
const PORT = process.env.PORT || 4242;
app.use('/', require('./routes/home_route'));
app.listen(PORT, () => {
console.log(`serveur démaré: localhost:${PORT}`);
});
home_controller.js code :
'use strict';
const homeView = (req, res) => {
res.render("home_view", {
} );
}
module.exports = { homeView };
home_route.js code :
'use strict';
const express = require('express');
const { homeView } = require('../controllers/home_controller');
const router = express.Router();
router.get('/home', homeView);
module.exports = router;
And home_view.ejs is just html. I don't understand where my mistake is, the code seems correct to me. Thank you in advance for your answers.
The problem is that you don't have any route handler for /. You are only handling /home. What you are saying with this line app.use('/', require('./routes/home_route')); is that every time I receive a request on /, I passe it to that router inside home_route.js, which only handles /home.
One way to solve this is to redirect the request you get on / to /home which is already handled. For that change home_route.js to:
const express = require('express');
const { homeView } = require('../controllers/home_controller');
const router = express.Router();
router.get('/home', homeView);
router.get('/', (req, res)=> res.redirect('/home')); // line I added
module.exports = router;
I have an express app like so:
// index.js
const express = require('express');
const app = express();
const userRoutes = require('./routes/userRoutes');
app.use('/user', userRoutes);
const verifyToken = (req, res, next) => {
// validate req.cookies.token
next();
}
And I'm using an express router module like this:
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
router.get('/:userid/data', verifyToken, async (req, res) => {
const data = await db.query()
res.json(data)
});
Obviously this doesn't work because verifyToken is not accesible within the module. How can I use the same verifyToken middleware function throughout different express modules?
Move verifyToken to a different file and export it from there.
Then you can import it in other places.
One thing that you can do, that works well is to group all your authed routes under a common path and use router.use to make sure that you apply the verifyToken middleware on all of them.
I am not running into any errors but I am wondering if this is the correct way to use two or more route.js files using express.Router. Am I using module.exports = router correctly as they are in two separate files, or is there a different way?
app.js
const express = require("express");
const api = require("./routes/tracking.route");
const user = require("./routes/user.route");
const app = express();
app.use("/api", api);
app.use("/user", user);
tracking.route.js
const express = require("express");
const router = express.Router();
const tracking_controller = require("../controllers/tracking.controller");
router.get("/list", tracking_controller.tracking_list);
module.exports = router;
user.route.js
const express = require("express");
const router = express.Router();
const User = require("../models/user.model");
router.post("/signup", ...");
module.exports = router;
I'm structuring my code to become more readable and maintainable at the same time.
here is my GET.articles and my INSERT.articles is just the same with this.
const express = require('express');
const router = express.Router();
router.get('/sample', (req, res) => {
res.send("Nice")
})
module.exports = router;
my index.js
const GET_articles = require('./GET.articles');
const INSERT_articles = require('./INSERT.articles');
exports { GET_articles, INSERT_articles}
and I import it like this:
app.use('/example', require('./routes/articles_controller/index'));
This is my error:
SyntaxError: Unexpected token export
Look at your first block of code:
module.exports = router;
Do that.
Change:
exports { GET_articles, INSERT_articles}
to
module.exports = { GET_articles, INSERT_articles}
If you want to use import and export then see this question.
Then note that a plain object isn't something you can just use.
You should use the routers and not the object containing them.
const routers = require('./routes/articles_controller/index');
app.use('/example', routers.GET_articles);
app.use('/example', routers.INSERT_articles);
app.js file
const express = require('express');
const router = express.Router();
const exampleRoute = require('./routes/articles_controller/index');
var app = express();
app.use('/', router)
app.use('/example', router, exampleRoute);
router.get('/sample', (req, res) => {
res.send("Nice")
})
app.listen(3000, ()=>{
console.log("Listening on port 3000")
})
route file
const GET_articles = require('./GET.articles');
const INSERT_articles = require('./INSERT.articles');
module.exports = [GET_articles, INSERT_articles]
GET articles files
module.exports = function getArticle (req, res) {
//Logic as required goes here
res.send("Content to be rendered")
}
I'm trying to start my Node.js server, I have 2 files: my app.js
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
morgan = require('morgan'),
consign = require('consign'),
cors = require('cors'),
passport = require('passport'),
passportConfig = require('./passport')(passport),
jwt = require('jsonwebtoken'),
config = require('./index.js');
app.use(express.static('.'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cors());
app.use(passport.initialize());
app.set('playersecret', config.secret);
consign({ cwd: 'services' })
.include('Player/app/setup/')
.then('Player/app/api/')
.then('Player/app/routes/')
.into(app);
module.exports = app;
and /app/routes/auth.js
const models = require('#Player/app/setup');
module.exports = (app) => {
const api = app.PlayerAPI.app.api.auth;
app.route('/',).get((req,res) => res.send('Player API'));
app.post('/api/auth/',api.login(models.User));
}
and as I understood my routes are not imported to app.js, because if I write code right in app.js, it works fine.
How do I import it right?
The way you have your auth.js routes defined is that it accepts the app instance, so you would need to do the following in your app.js:
const express = require('express')
const authRoutes = require('./app/routes/auth.js')
const app = express()
// ...
authRoutes(app)
Alternatively you can just inline the require although I find that messy (personal opinion):
const express = require('express')
const app = express()
// ...
require('./app/routes/auth.js')(app)
A better approach would be to export a router object:
/app/routes/auth.js
const express = require('express')
const models = require('#Player/app/setup')
const api = require('./path/to/PlayerAPI.js')
const router = express.Router()
router.get('/', ...)
router.post('/', api.login(models.User))
module.exports = router
app.js
const express = require('express')
const authRoutes = require('./app/routes/auth.js')
const app = express()
// ...
app.use('/api/auth', authRoutes)
If you want to import a js file, you have to include the file name at the beginning of your app.js as show below.
var express = require('express')
var auth = require(./app/routes/auth.js)
you can know more about importing in javascript file in express.js official document file.