Route parametrs empty in Express - javascript

I try print router parametrs but req.params is empty, don't know what I'm doing wrong.
In app.js:
...
var shareFile=require('./controllers/file/share');
...
app.use('/share/:id', shareFile);
...
And share.js controller:
var express = require('express');
var router = express.Router()
router.get('/', function (req, res, next) {
res.send(req.params)
});
module.exports = router;
localhost:3000/share/123 gives empty json page. Changing res.send to console.log gives {}.
Thanks

req.params will produce {id: 'abc'} when the routing is defined as /share/:id and you made the call to http://yourserver/share/abc
router.get('/', function (req, res, next) {
res.send(req.params)
});
Above you should expect that req.params will be empty here because your are not expecting them. But you should see them here:
router.get('/share/:id', function (req, res, next) {
res.send(req.params)
});

Related

Express.js main router working, but others routers on him not

I have the problem on routers. My main route /weather working, but others routers on him don't.
app.js
const express = require('express');
const weatherRoute = require('./back/routes/weatherRouter.js');
const app = express();
app.use(bodyParser.json());
app.disable('etag');
app.use('/weather', weatherRoute);
weatherRouter.js
const router = express.Router();
router.get('/', async (req, res) => {
try {
const wholeData = await WeatherInfo.find();
res.json(wholeData);
} catch (err) {
res.json({ message: err })
}
});
router.get('/now', (req, res) => {
res.send("ITS NOT WORKING");
});
module.exports = router;
the problem is that localhost:5000/weather working perfect, but when I want to use some other routers on that Route e.g. localhost:5000/weather/now that's not working
Any ideas what I'm doing wrong ?
UPDATED :
it works, when between those routers is no others routers.
e.g.
router.get('/', async (req, res) => {
//working
}
router.post('/:add', async (req, res) => {
//working
}
router.get('/now', async (req, res) => {
//doesnt work
}
If I move /now above /add router it works perfect. Can someone explain why is this happening ?
Define actual path in path section likerouter.post('/weather/now', (re, res) => {
//Handel re
}
I found the solution.
The routers position is matter. Reference to explanation
My last router didn't work, because another router already catched him.
app.get('/:add', function (req, res) {
// this will match all /a, /b .. including /new
res.end('done!');
});
app.get('/now', function (req, res) {
// this is never called
res.end('done!!');
});

Route requiring a middleware function

I'm creating my routes module in nodejs with socket.io
var express = require("express"); // call express
var taskSchema = require("../models/taskModel");
var mongoose = require("mongoose");
var router = express.Router(); // get an instance of the express Router
module.exports = function (io) {
router.use(function (req, res, next) {
io.sockets.emit('payload');
console.log("Something is happening.");
next();
});
router
.route("/tasks")
.post(function (req, res, next) {
...
});
router
.route("/tasks")
.get(function (req, res) {
...
});
};
When I compile server I get this error
TypeError: Router.use() requires a middleware function but got a undefined
It appears to me that the problem is probably in the code that loads this module because you never export the actual router. So, assuming you do app.use() or router.use() in the caller who loads this module, your aren't returning the router from your function so there's no way to hook that router in and you would get the error you see.
I'm guessing that you can fix this by just returning the router from your exported function:
var express = require("express"); // call express
var taskSchema = require("../models/taskModel");
var mongoose = require("mongoose");
var router = express.Router(); // get an instance of the express Router
module.exports = function (io) {
router.use(function (req, res, next) {
io.sockets.emit('payload');
console.log("Something is happening.");
next();
});
router
.route("/tasks")
.post(function (req, res, next) {
...
});
router
.route("/tasks")
.get(function (req, res) {
...
});
return router; // <=========== Add this
};
Then, when you do:
let m = require('yourModule');
router.use(m(io));
Then function will return the router that router.use() will be happy with. You can pass either middleware or a router to .use().
If this guess isn't quite on target, then please show us the code that loads and calls this module.
When that function is called it's gonna return the equivalent of undefined. Also, normally a route is defined before the endpoint. It's typically structured like:
let myRouter = new Router();
Router.use('something', middlewareFunction, someotherprocess);

Express js 4x :req.params returns empty object

Trying to get URl parameters in express js,but got empty object.
var password= require('./routes/password');
app.use('/reset/:token',password);
password.js
router.get('/', function(req, res, next) {
console.log(req.params);
res.send(req.params);
});
console.log(req.params) output is {}
Access url :http://localhost:3000/reset/CiVv6U9HUPlES3i0eUsNwK9zb7xVZpfHsQNuzMNWqLlGA4NJKoagwbcyiUZ8
By default, nested routers do not get passed any parameters that are used in mountpaths from their parent routers.
In your case, app is the parent router, which uses /reset/:token as a mountpath, and router is the nested router.
If you want router to be able to access req.params.token, create it as follows:
let router = express.Router({ mergeParams : true });
Documented here.
You are getting params and query mixed up.
Query approach
Your code should look like this when using query values for the example url: www.example.com?token=123&foo=bar
router.get('/', function(req, res, next) {
console.log(req.query);
console.log(req.query.token); // to log value of token
console.log(req.query.foo); // to log value of foo
res.send(req.query);
});
Params approach
Your code should look like this when using params values for the example url: www.example.com/123
router.get('/:token', function(req, res, next) {
console.log(req.params);
console.log(req.params.token); // to log value of token
res.send(req.params);
});
Instead you can use a middleware to log the path params:
const logger = (req, res, next)=>{
console.log(req.params)
res.send(req.params)
next()//<----very important to call it.
};
app.use(logger); //<----use to apply in the app
router.get('/', (req, res, next)=>res.send('Logged.'));
Actually you messed it up a little bit. You have to pass instance of express to your module.
Server.js:
//adding modules
require('./routes/password')(app);
Password.js:
module.exports = function(router) {
router.get('/reset/:token', function(req, res, next) {
console.log(req.params);
res.send(req.params);
});
//and so on.. your routes go here
}

Generator Function not being executed

Why is my api not being called when I define my get function as a generator function?
This works:
router.get('/', function(req, res){
res.send('this works');
});
This also works:
router.get('/', get);
function get(req, res){
res.send('works!');
}
This does not work:
router.get('/', get);
function* get(req, res){
res.send('does not work!');
}
Rest of the file...
var express = require('express');
var router = express.Router();
//setting up the get route as above
module.exports = router;
Koa is built to work with generators so you may have more luck with that.

Router.use requires middleware function?

So I'm trying to seperate my login routes in a seperate JS file called login_routes.js
I keep getting this specific error:
TypeError: Router.use() requires middleware function but got a Object
at Function. (/Users/ethanthomas/Desktop/mean-stuff/express-server/node_modules/express/lib/router/index.js:446:13)
Not entirely understanding what it's asking me to implement?
login_routes.js:
var express = require('express');
var app = express();
app.route('/login')
.get(function(req, res, next) {
res.send('this is the login form');
})
.post(function(req, res, next) {
console.log('processing');
res.send('proccessing the login form!');
});
server.js:
var express = require('express');
var app = express();
var path = require('path');
var adminRoutes = require('./app/routes/admin_routes');
var loginRoutes = require('./app/routes/login_routes');
app.use('/admin', adminRoutes);
app.use('/login', loginRoutes);
//send our index.html file to the user for the home page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
//start the server
app.listen(1337);
console.log('leet is the magic port');
Your login_routes.js should look something like this (in the context of express):
var express = require('express');
var router = express.Router();
// GET request to /login
router.get('/', function(req, res, next) {
// do something
});
// POST request to /login
router.post('/', function(req, res, next) {
// do something
});
module.exports = router;
In your app.js you use
var login_routes = require('./login_routes');
...
app.use('/login', login_routes);
...
Have a look at the code generated by the express-generator module. That is a starting point for express webserver apps.
People have already offered hints at the solution in comments.
The first issue is that you need to export your "sub" app from login_routes.js. To do so, change this:
var app = express();
Into this:
var app = module.exports = express();
Secondly, you are—probably unintentionally—creating routes for GET /login/login and POST /login/login. To solve this, use this in login_routes.js:
app.route('/').get(...).post(...);
This is because the root path in your sub app (the one in login_routes.js) will get mapped to the path used in app.use() in your main app (server.js).
Do like this:
login_routes.js:
exports.get = function( req, res ) {
res.send('this is the login form');
};
exports.post = function( req, res ) {
console.log('processing');
res.send('proccessing the login form!');
};
server.js:
var loginRoutes = require('./app/routes/login_routes');
app.get('/login', loginRoutes.get);
app.put('/login', loginRoutes.post);
login_routes.js:
var express = require('express');
var app = express();
app.route('/login')
.get(function(req, res, next) {
res.send('this is the login form');
})
.post(function(req, res, next) {
console.log('processing');
res.send('proccessing the login form!');
});
module.exports = router;
just writ module.exports = router then it will be work

Categories

Resources