Access param from app.use in controller - express

I want to access a param defined in my app.use (index.js) inside my app.get (idCtrl.js). Below I have an boiled down version of my code. The route works and sends me to the controller for a url such as /1234 but I can't access :id from req.params.
index.js
var express = require('express');
var app = express();
var idCtrl = require('./idCtrl');
...
app.use('/:id([0-9]{4})', idCtrl);
idCtrl.js
var express = require('express');
var router = express.Router();
...
router.get('/', function(req, res){
// I wanna access :id from the app.use in index.js
});
...

The proper way to handle that situation is
First, set up your param
router.param('id',function(req,res,next,id)
{
//d owhatever you want with your param here
req.paramID = id; // save it in your req
next(); // Continue to your get('/:id')
};
Then, set up the route using the param
router.get('/:id', function(req, res){
console.log(req.paramID); // You got your param here
});

Related

routes in exported router not available in app

I'm trying to export a router 'Accounts' to use in my app. The 'Accounts' router has the paths '/login' (POST), '/register'(POST), 'login' (GET), and '/logout' (POST). In my index app I am using the router with the path '/account'. So the paths should be:
/account/login (POST)
/account/login (GET)
/account/register(POST)
/account/logout (GET)
But when I call these paths they aren't found by the app:
How do I get the paths in the 'accounts.js' router to work in the 'index.js' app?
My file structure is like this:
my account.js file looks like this:
const express = require('express');
const passport = require('passport');
const Account = require('../models/Account');
const Branch = require('../models/Branch')
const router = express.Router({mergeParams: true});
const registerAccount = (req, res, next) => {
//register the account
};
const createUser = (req,res) => {
//create a user in another db
}
router.post('/register',
[registerAccount, createUser]);
router.get('/login', function(req, res) {
res.json(user);
});
router.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: 'account/login' }));
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
});
module.exports=router;
and my index.js looks like this:
// index.js
var express = require("express");
var bodyParser = require("body-parser");
var jwt = require("jwt-simple");
var auth = require("../auth/auth.js")();
var users = require("./users.js");
var cfg = require("../config.js");
const accountController = require('./account');
var app = express();
app.use(bodyParser.json());
app.use(auth.initialize());
app.use('/account',accountController);
app.get("/", function(req, res) {
res.json({
status: "My API is alive!"
});
});
app.post("/token", function(req, res) {
//some token stuff that doesn't matter here
});
module.exports = app;
For starters, you don't pass an array to a router.post(), so change this:
router.post('/register', [registerAccount, createUser]);
to this:
router.post('/register', registerAccount, createUser);
And make sure that registerAccount calls next() when it's done and wants createUser() to get called.
In the doc, for this syntax:
app.post(path, callback [, callback ...])
the brackets in [, callback] mean that parameter is optional. The brackets are not supposed to be used.

Mean Stack Root Routing is not working

Can someone help me why default route is not working in my Mean App, But the next routing works
Here when I open http://localhost:3000 I am not able to see any output, But I have defined route in route.js which is working
var express = require('express');
var cors = require('cors');
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
const port = 3000;
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
When I open the page with http://localhost:3000/main I am able to see the Output and also log written in the console
const express = require('express');
const router = express.Router();
router.get('/main', function (req, res, next) {
res.send('This is the Admin Landing Page');
});
router.get('/install', function (req, res, next) {
res.send('This is the Install Landing Page');
console.log('Opened the Install path');
});
module.exports = router;
It looks like you the code you pasted is the full version, and it's not runnable because:
You did not declare app variable.
You did not start the http server.
It's really hard to tell the root cause what's wrong of your code. Following codes works for me:
const express = require('express');
const port = 3000;
let app = express();
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
let server = require('http').createServer(app);
server.listen(port, function() {
console.log('Server started');
});

Express route function not showing text

app.js :
var index = require('./routes/index2');
var users = require('./routes/users');
app.use('/', index);
app.use('/users', users);
index2.js :
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
when I go to localhost:3000/ I don't see the text in send function
I guess your browser is you waiting for a response?
If you change index2.js to be a function and return the router, you'll be adding it as a middleware with app.use('url', middleware). I hope this helps
app.js
var index = require('./routes/index2');
var users = require('./routes/users');
app.use('/', index()); //Invoke the object to get the router back
app.use('/users', users);
index2.js
var express = require('express');
var router = express.Router();
module.exports = function() {
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
return router;
};
Returning the router from index2 to be used as a middleware

router vs app in express 4.0

I am learning express js 4.0 and building compact CRUD REST API web application with it. In the tutorial, it shows two ways; using app and using router.
//using router
var router = express.Router();
router.get('/', function(req,res){
res.send('hello, world')
});
//using app
app.get('/', function(req,res){
res.send('hello, world')
});
To me, I feel they work same but I don't know why people use router, I think using app is more simple. Can anybody explain what is difference between them?
It allows for modularity. A lot of people have a routes folder that they keep all their route handlers in. And then in their app.js file, they just do something like app.use(<prefix>, <routes>); after they require their router. It keeps your files smaller and more organized.
Example:
app.js
var express = require('express');
var rootRoutes = require('./routes/index');
var userRoutes = require('./routes/user');
var app = express();
app.use('/', rootRoutes);
app.use('/user', userRoutes);
module.exports = app;
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('index.jade');
});
router.get('/about', function(req, res) {
res.render('about.jade');
});
module.exports = router;
routes/user.js
var express = require('express');
var router = express.Router();
router.get('/:name', function(req, res) {
var userName = req.params.name;
res.render('user.jade', {
userName: userName
});
});
module.exports = router;

How to stop losing request parameters in expressjs?

I have defined my route in a separate route.js file as below (details removed for brevity)
var express = require('express');
var router = express.Router();
router.route('')put(function(req, res){
console.log(req.params.id); //prints undefined
});
and in server.js I map this route as below
var route = require('./routes/route.js');
app.use('/api/use/:id/role', route);
My route function is correctly invoked but the id parameter is not available in the router handler. Am I doing anything wrong?
Use the mergeParams option:
var router = express.Router({ mergeParams : true });
Full standalone example:
var express = require('express');
var app = express();
var server = app.listen(3000);
var router = express.Router({ mergeParams : true });
router.route('').get(function(req, res) {
console.log('id', req.params.id);
return res.sendStatus(200);
});
app.use('/api/use/:id/role', router);