I would like to check the route when receiving a request in nodejs (10.16) and express (4.16) project. The server listens to port 3000 on localhost. Here is a users route:
const users = require('../routes/users');
module.exports = function(app, io) {
app.use('/api/users', users);
}
In route users.js, there is:
router.post('/new', async (req, res) => {...}
When a route is called (ex, ${GLOBAL.BASE_URL}/api/users/new), how do I know which route is being called from the param req?
OK, what I understand, you are having troubles accessing your user routes (declared in your users.js file) from your application root file.
Because you are modularize your routes, you need to make sure you export your routes module to gain access from another file:
app.js:
const UserRouter = require('../routes/users');
module.exports = function(app, io) {
app.use('/api/users', UserRouter);
}
users.js:
const UserRouter = express.Router()
UserRouter.post('/new', async (req, res) => {...};
module.exports = UserRouter;
If you need the path of request, Try this:
var path = url.parse(req.url).pathname;
console.log('path:', path);
Related
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);
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
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
I m still trying to learn NodeJs but I came across this path thing I encountered in Express. When I create an app using Express I noticed that in app.js I have these lines of code var index = require('./routes/index');
var users = require('./routes/users');
app.use('/', index);
app.use('/users', users);
And in users.js I already have configured
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
I don t really understand why is it in users.js router.get('/') instead of router.get('/users') as it is specified in app.js? Can someone explain a bit what s going on in this case?
As far as I understand in app.js it says whenever someone tries to access the specified route('/users') lets say localhost:3000/users in the browser, let the file required in users variable handle it.
If you are working with routes the express app is automatically . Here is an example from the express.js website:
In our router file we have:
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) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
Then in our main file were we have our server etc we load in the router:
var birds = require('./birds')
// ...
app.use('/birds', birds)
These routes in the router app are only accessed when there is a request to to /birds url. All the routes in the router are now automatically staring with /birds
So this code in the express router:
// im code in the birds router
router.get('/about', function (req, res) {
res.send('About birds')
})
Is only executed when someone makes a get request to the /birds/about url.
More information in the official express.js docs
I would just like to point out what I have learnt today after some frustration, and maybe somebody can elaborate as to why this happens. Anyway, if, like me, you want to use '/users' for all user routes or '/admin' for all administrator routes then, as WillemvanderVeen mentioned above, you need to add the following code to your main app.js file
var users = require('./routes/users')
app.use('/users', users)
However, one thing which was not mentioned is that the order with which you declare your 'app.use('/users', users)' in app.js is important. For example, you would have two route handling files as so:
/routes/index.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => { res.render('index') });
/routes/users.js
const express = require('express'); const router = express.Router();
router.get('/', (req, res) => { res.send('users route') })
You would then require them in your main app.js file as so:
app.js
const express = require('express');
const app = express();
const index = require('./routes/index');
const users = require('./routes/users');
app.use('/', index);
app.use('/users', users);
and you would expect that when you hit the '/users' route that you would receive the res.send('users route') page.
This did not work for me, and I struggled to find any solution until recently, which is why I am now commenting to help you.
Instead, I swapped the app.use() declarations in app.js around like so and it worked:
app.js
const express = require('express');
const app = express();
const index = require('./routes/index');
const users = require('./routes/users');
app.use('/users', users);
app.use('/', index);
Now when I hit '/users' I see the 'users route' message. Hope this helped.
To answer your question though, when you configure the route handler in app.js as users, then you are requiring a router file (./routes/users) to handle all requests from that file and sending them to the URL /users first. So if you do the following:
/routes/users.js
router.get('/dashboard', (req, res) => {
// get user data based on id and render it
res.render('dashboard')
});
then whenever user is logged in and goes to dashboard, the URL will be /users/dashboard.
New to Node/Express, trying to figure out what the best way to make my server controllers organized and modular. I have app.js file with the following code.
var express = require('express');
var app = express();
// Launch Server
const PORT = process.env.PORT || 8888;
app.listen(PORT, function() {
console.log('Server running on port ' + PORT + '!');
});
// Render Static Views from the Public Directory/Views
app.use('/', express.static(__dirname + '/public/views/'));
// API
// var foo = require(bar);
I want to keep all of my API logic in apiController.js then require it into my app.js. What's the best way to do this?
Example GET Endpoint
app.get('/api', function(req, res) {
res.json({
success: true,
message: 'Hello World!'
});
});
Here is my project structure:
I like David Fang's solution, but I would go one step further and create an Express 4 router for your API routes. They're very composable and modular, as they can act as both routers and middleware, can be nested and imported neatly.
app.js
var apiRouter = require('./controllers/apiController.js');
app.use('/api', apiRouter);
apiController.js
var express = require('express');
var apiRouter = express.Router();
apirouter.get('/some/route', (req, res) => {
// some code...
})
module.exports = apiRouter;
Documentation: http://expressjs.com/en/api.html#router
Here's a simple method:
app.js
require('./controllers/apiController.js')(app);
apiController.js
module.exports = function(app) {
app.get('/api/some/route', function(req, res) {
// some code...
}
}
Maybe this is not the best approach, but I have used it without problem in small apps.
This is how i do it
I have app/controllers/index which call register method each of the controller. Each controller has a register method that register its route with the app.
In controllers:
exports.register = function(app) {
app.post('/login', login)
}
In controllers index.js or routes or whatever you want to name it.
require('../controllers/auth').register(app)
require('../controllers/registration').register(app)
and at the end, drops all other routes to 404.