Cannot enter router get in express - node.js

I am trying to use routers in my Node js application. I cannot execute router.get functiom
In the main file which is server.js I used this script
// Routes
app.use('/api/v1/stores', require('./routes/stores'));
But in the route file which is stores.js, I cannot enter the router.get function and execute it
const express = require('express');
const router = express.Router();
console.log("I can reach this point")
router.get('/', (req, res) => {
console.log("I can not reach this point")
res.send('app/about');
});
module.exports = router;

That's because new express version 4.17.* is different when handling routes. try,
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('app/about');
});
module.exports = app;
For more details: https://expressjs.com/en/guide/routing.html
you can try this way also, in your store.js file create something like this.
module.exports = app => {
app.get('/', (req, res) => {
res.send('app/about');
});
}
and add this require to server.js
require('./store')(app);

Related

why does express middleware not working in separate files

I want to broke down my routers into separate file rather than keeping all API routes in a single file. So i tried to identify user URL using a middle ware and call the api according to the url as you seeing bellow but middleware function is not working . how to solve this?
//HERE IS INDEX.jS file CODE
const express = require("express");
const dotenv = require("dotenv");
const app = express();
const PORT = process.env.PORT || 7000;
app.listen(PORT);
app.use("/users", require("./routes/users/users"));
//==========================================================
//HERE IS users.js FILE CODE
const express = require("express");`enter code here`
const router = require("express").Router();
express().use(selectApi);
function selectApi(req, res, next) {
console.log("this line also not executing")
switch(req.originalUrl){
case '/':
// calling api here from a nother separate file
case '/user/:id'
// calling api here from a nother separate file
}
}
module.exports = router;
There is an example in the Express.js Routing Guide. I've modified it slightly to fit your example.
users.js
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
// calling api here from a nother separate file
})
router.get('/user/:id', function (req, res) {
// calling api here from a nother separate file
})
module.exports = router
index.js
const express = require("express");
const dotenv = require("dotenv");
const app = express();
const PORT = process.env.PORT || 7000;
app.listen(PORT);
app.use("/users", require("./routes/users/users"));

Why express.Router() while separating routes

I have gone through express document in that i have learn about
Router() and express.Router(). so my question is i have separated
my all routes from main app and created different folder there i did
not create any router object(var router express.Router()) for
routing to specific path still it's working fine. So i want to know
why this Router class is necessary ?
see, This is main app file,
'use strict'; const startUpDebugger=require('debug')('app:startUp');
const dbDebugger=require('debug')('app:db'); const express =
require('express'); const app = express(); const
moragan=require('morgan'); const helmet=require('helmet'); const
config=require('config'); const courses=require('./routes/courses');
const home=require('./routes/home'); app.use(helmet());
app.set('view engine','pug'); app.set('views','./view');
app.use(express.json()); app.use('/api/courses',courses);
app.use('/',home);
console.log(Node enironment variable: ${process.env.NODE_ENV});
console.log(Application name : ${config.get('name')});
console.log(mail server : ${config.get('mail.host')});
if(app.get('env')==='development'){
app.use(moragan('tiny'));
startUpDebugger("******Morgan enabled*******") }
const port = process.env.PORT || 5000; app.listen(port);
console.log(Api Node running on port ${port});
This is my courses.js which is my route file
const express=require('express'); const app=express
const courses=[{"id":1,"course":"course1"},
{"id":2,"course":"course2"},
{"id":3,"course":"course3"},
{"id":4,"course":"course4"}]
app.route('/posting').post((req,res)=>{
console.log(req.body);
courses.push(req.body)
res.status(201).send(courses); }).put((req,res)=>{
res.send("Successfully put message") }) app.get('/sub/:id',(req,res)=>{
res.status(200).send(req.params); })
module.exports=app;
your question is not clear but if i am getting you right:-
If your app is really simple, you don't need routers.
//you can just invoke express constructor and use it
const app=express()
app.get('/', function (req, res) {
res.send('root')
}) // app.get,app.post and so on
in your main app file.
But as soon as it starts growing, you'll want to separate it into smaller "mini-apps", so that it's easier to test and maintain, and to add stuff to it. You'll avoid a huge main app file :) .
so here you need to make another file for routes and have to invoke express.Router() class and use it
like:
//route.js
const Router=express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
And import this file into the main app file and pass it to middleware to use
app.use('/',require('./routes/routes.js'))
and comparing to express() object the express.Router() object is light weight

How to app use all routes from different file

I'm trying to separate my routes, previously i'm including them to my app.js
/backend/app.js
const express = require("express");
const router = require("./routes");
const status = require("./routes/status");
const register = require("./routes/register");
const login = require("./routes/login");
app.use('/', router);
app.use('/status', status);
app.use('/login', login);
app.use('/register', register);
I realized its not ideal since i am adding more and more routes later on and the app.js will be polluted with them
What i want to do now is just to import an index.js to app.js and basically this index have all the routes needed
/backend/routes/index
const routes = require("express").Router();
const root = require("./root");
const status = require("./status");
const register = require("./account/register");
const login = require("./account/login");
routes.use("/", root);
routes.use("/login", login);
routes.use("/register", register);
routes.use("/status", status);
and now in the app.js i can just include the index
const routes = require("./routes");
app.use('/', routes);
but its not working im getting 404 error when trying to request to login route
im exporting them like this
module.exports = routes;
In your app.js
app.use('/', require('./backend/routes/index'))
Then, in your routes/index
import express from 'express'
const router = express.Router()
// GET /
router.get('/', function (req, res) {
})
// GET /countries
router.get('/countries', (req, res, next) => {
})
// POST /subscribe
router.post('/subscribe', checkAuth, generalBodyValidation, (req, res, next) => {
})
// All routes to /admin are being solved in the backend/routes/admin/index file
router.use('/admin', require('./backend/routes/admin/index'))
module.exports = router
Your admin/index file can be
import express from 'express'
const router = express.Router()
// POST /admin/login
router.post('/login', (req, res, next) => {
})
module.exports = router
With this, you will be able to perform a POST request to /admin/login.
Hope this solves your problem, if it does mark my answer as correct, if not tell me what went wrong and I will solve it :D

How can I separate route files?

I have a route file in my project and it is called from my app with these lines:
var index = require('./routes/index');
app.use('/', index);
But I need to separate the route file, and I'm trying to do this:
var index = require('./routes/index');
var user = require('./routes/user');
app.use('/', index);
app.use('/user', user);
In route user.js I put the service that I need to access from the client. But it's not working. I don't know what is wrong, I am a beginner in Node.js.
The request returns:
GET /user/find 304 4.203 ms - -
And user.js file is:
var router = express.Router();
router.get('/user/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
*This request works well on index.js
You put user router under /user route, and in your user router you defined app.get('/user/find'), so the actual path would be /user/user/find, you need to remove the user prefix in router
var router = express.Router();
router.get('/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
A simple way to do this can be:
index.js
var express = require('express')
var app = express()
var route1 = require('./route1')
var route2 = require('./route2')
app.use('/', route1);
app.use('/hello', route2);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
route1.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route1');
})
module.exports = router
route2.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route2');
})
module.exports = router
Have you made sure to include a module.exports = router at the end of each of your route files?
Your route files should be set up thusly:
var router = require('express').Router();
router.get("/example", function (req, res) {
res.send("Hello");
});
module.exports = router;

Express Middleware Issue

On routes/index.js it works fine if I leave the module.exports = routes;
But If I change it to the following to allow multiple files then I get a middleware error:
module.exports = {
routes
};
var app = express();
const routes = require('./routes');
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use('/', routes);
app.get('/', (req, res) => {
res.send('Please visit: http://domain.com');
}, (err) => {
res.send(err);
});
//routes/index.js
const routes = require('./MainRoutes');
module.exports = routes;
//routes/Main Routes.js
const routes = require('express').Router();
routes.post('/main', (res, req) => {
//code here works
});
module.exports = routes;
The error is: Router.use() requires middleware function but got a ' + gettype(fn));
MainRoutes.js exports the express router object, which middleware will understand just fine if you do
module.exports = routes; // routes/index.js
However, when you do
module.exports = {
routes
};
You are now nesting that router object in another object, which middleware can't understand.
In your main server file you can do
const {routes} = require('./routes');
to get the router object properly.
Modify the routes/index.js as:
const routes = require('express').Router();
routes.use('/main', require('./MainRoutes'));
// Put other route paths here
// eg. routes.use('/other', require('./OtherRoutes'))
module.exports = routes;
Modify the Main Routes.js as:
const routes = require('express').Router();
routes.post('/', (res, req) => {
// route controller code here
});
module.exports = routes;
Hope this helps you.

Resources