Express routes issue - javascript

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.

Related

Which part of the Router code provides the TypeError: requires Middleware function but got a Object

In this fictive project I am trying to set up the Routing structure. Although I used module.exports in both files, running a test still gives me the following error:
TypeError: Router.use() requires a middleware function but got a Object
My Code:
Minions.js
const minionsRouter = require('express').Router();
module.exports = minionsRouter;
const {
getAllFromDatabase,
addToDatabase,
getFromDatabaseById,
updateInstanceInDatabase,
deleteFromDatabasebyId,
} = require('./db.js');
minionsRouter.get('/', (req, res, next) => {
const minionsArray = getAllFromDatabase('minions');
if (minionsArray) {
res.status(200).send(minionsArray);
} else {
res.status(404).send();
}
});
API.js
const express = require('express');
const apiRouter = express.Router();
const minionsRouter = require('./minions');
const ideasRouter = require('./ideas');
const meetingsRouter = require('./meetings');
apiRouter.use('/minions', minionsRouter);
apiRouter.use('/ideas', ideasRouter);
apiRouter.use('/meetings', meetingsRouter);
module.exports = apiRouter;
Server.js
const express = require('express');
const app = express();
module.exports = app;
/* Do not change the following line! It is required for testing and allowing
* the frontend application to interact as planned with the api server
*/
const PORT = process.env.PORT || 4001;
// Add middleware for handling CORS requests from index.html
const cors = require('cors');
app.use(cors());
// Add middleware for parsing request bodies here:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// Mount your existing apiRouter below at the '/api' path.
const apiRouter = require('./server/api');
app.use('/api', apiRouter);
// This conditional is here for testing purposes:
if (!module.parent) {
// Add your code to start the server listening at PORT below:
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`)
})
};
Any help is much appreciated!

Formatting for express routes in various files?

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.

How do you use two or more route.js files in Express Router in Node?

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;

Routes navigation is not working in NodeJs

I am using router in my NodeJs app.When I am trying to navigate it is unable to navigate to the given page.
Register.js is placed in routes folder and server.js is placed in parent directory.
Here is my code:
Server.js
const express = require('express');
const app = express();
app.set('view engine','ejs');
app.use(require('./routes/register'));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
var app = express();
router.use(bodyParser.json);
router.use(bodyParser.urlencoded({extended:true}));
router.get('/users', (req,res) => {
console.log('Hello there');
});
module.exports = router;
Now when I run this code and go to localhost:3000/users nothing happens and not even error shows in console.
Please let me know what I am doing wrong in above code.
Use router.use(bodyParser.json()); in register.js.
You have used body-parser at wrong place. Also you should initiate those with express instances always.
Also check your file name you have imported. Reigster -> register
Updated code:
Server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine','ejs');
app.use(require('./Register'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
router.get('/users', (req,res) => {
console.log('Hello there');
res.sendStatus(200)
});
module.exports = router;

How do i retrieve POST request data in a controller Node JS

route (routes/account.js)
const express = require('express');
const router = express();
var account_controller = require('../controllers/accountController');
router.post('/account/Getuser', account_controller.get_user);
controller (controllers/accountController.js)
exports.get_user = function (req, res) {
res.send(req.body.name);
};
Postman POST Request body
{
"name":"Isaac Gyasi Nimako"
}
Error Report
Cannot read property 'name' of undefined
you probably don`t have body-parser
const bodyParser = require('body-parser')
router.use(bodyParser.json())
You have to use the body_parser library
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
here is a very simple example from my GitHub
https://github.com/odaymard/Restful-CRUD-API-with-Node.js-Express/blob/master/server/server.js

Categories

Resources