I've been working with Express 4 and I just tried to use a namespaced route, but I wanted the namespaced route to have a param.
For instance:
/:username/shows
/:username/shows/:showname/episodes
etc etc. So with this, I thought this would be a good fit for express namespacing.
Router = require("express").Router;
userRouter = Router();
userRouter.route("/shows").get(function(req,res){ ... });
app.use("/:param", userRouter);
This would get the page to load as expected at /:username/shows, however the req.params, where I'd normally expect to find a key called username was empty. Am I missing something? Where can I access these params?
In your code, :username param is used by app, not in userRouter.
You can only access that from app, or you can curry :username param information to userRouter by using app.params() function
app.param('username', function(req, res, next, username) {
req.username = req.params.username;
next();
});
app.use('/:username', userRouter);
userRouter.get('/show', function(req, res, next){
var username = req.username; // Here you can access;
res.send("DONE");
});
Related
I'm trying to write express middleware to check the validity of a JWT in the Authorization header. This seems quite easy but I don't want it to run on all routes (e.g. not on login/signup routers).
So, I'd like to specify in the router declaration that a route should require a valid token. E.g. something like this
const controllers = require('../controllers');
module.exports = (app) => {
app.post('/auth/signup', controllers.auth.signup.post);
app.post('/auth/login', controllers.auth.login.post);
app.get('/teams', controllers.teams.get, {requiresToken:true});
};
Except, .post and .get don't take a third parameter and the controller only takes (req,res,next) parameters so I can't really see a way of passing startic data for each route. I'm sure I'm missing something simple
This is how i created a middleware to pass the data into
module.exports = function(options) {
return function (req, res, next) {
//write your code here
// here you can access options variable
console.log(options.data)
next();
}
}
How you call that middleware is like this
app.use(middleware({'data' : 'Test'}));
To use on route basis
app.post('/userRegistration', middleware({'data' : 'Test'}), (req, res) => {});
You can exclude the auth subroute from this middleware using negative lookup regexp:
const controllers = require('../controllers');
module.exports = (app) => {
app.use(/\/((?!auth).)*/, yourJwtTokenValidatorMethod); // replace with your jwt token validator middleware
app.post('/auth/signup', controllers.auth.signup.post);
app.post('/auth/login', controllers.auth.login.post);
app.get('/teams', controllers.teams.get, {requiresToken:true});
};
I've been trying a variety of setups for hot reloading and one that I've come across is the https://github.com/glenjamin/ultimate-hot-reloading-example/. Modifying this boilerplate code as a starting point, I've come across the following problem in my server code:
// server.js
import chokidar from 'chokidar';
import express from 'express';
const app = express();
// this is the middleware for handline all of my routes
app.use(function (req, res, next) {
require('./server/index')(req, res, next);
// if I commented out any additional routes, the setup would work fine
require('./server/foo')(req, res, next);
require('./server/catch-all')(req, res, next);
});
//this watches the server folder for changes
const watcher = chokidar.watch('./server');
watcher.on('ready', function () {
watcher.on('all', function () {
console.log("Clearing /server/ module cache from server");
Object.keys(require.cache).forEach(function (id) {
if (/[\/\\]server[\/\\]/.test(id)) delete require.cache[id];
});
});
});
app.listen(3000, 'localhost', function (err) {
if (err) throw err;
const addr = this.address();
console.log('Listening at http://%s:%d', addr.address, addr.port);
});
The above is the server code that handles clearing the cache by watching for changes with the chokidar module. If I have just one route required inside the app.use middleware function (which listens for every incoming request), I can get it to work. However if have multiple routes, the following error occurs:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
This is a common issue posted on stack overflow, but all of the solutions I've come across and attempted haven't worked. My route files are as follows:
//index.js
import express from 'express';
const router = express.Router();
router.get('/', (req, res, next) => {
res.send("greagrehgarhegrehuh").end();
return next('router');
});
module.exports = router;
//end of index.js
//foo.js
import express from 'express';
const router = express.Router();
router.get('/foo', (req, res, next) => {
res.send("foo").end();
return next('router');
});
module.exports = router;
//end of foo.js
//catch-all.js
import express from 'express';
const router = express.Router();
router.get('*', (req, res, next) => {
res.send("catch all").end();
return next('router');
});
module.exports = router;
// end of catch-all.js
All three routes do the same thing, bar the endpoint. So far I've explicitly called end on each to end the response, used return next('router') to skip the rest of the middleware functions and have also tried doing it without the above as well. Any ideas on what I'm missing here to get this working? Here's a github project that showcases the issue
https://github.com/RonanQuigley/express-chokidar-hot-reload
UPDATE
So I actually removed the next calls and seem to have almost got it working by doing the following:
app.use(function (req, res, next) {
require('./server/index')(req, res, next);
require('./server/foo')(req, res, next);
});
// a second app.use middleware, that does the same
// as the catch all // * router.get from my original post
app.use(function (req, res, next) {
app.get('*', (req, res) => res.send('catch all'));
})
However, I can't use this second app.use with another require call to a file with an express router like the others. So it seems that express runs through the middleware stack, reaches the * and tries to set the header twice.
The reason I need the * is normally if a user requests an endpoint that doesn't exist, Node correctly shows up with cannot GET/. However, for some reason, with the setup I've outlined express will then crash. My workaround is using * at the end of the middleware stack and I'd just use a res.redirect to send the user back to wherever, but this causes the above issue I've outlined in my original post. So not sure how to get around that one.
So currently I have either:
1) Hot reloading works without the require for a router.get('*'), but when the user navigates to an endpoint that doesn't exist, express will crash.
2) Hot reloading works with the app.get('*') inside a second app.use call, but I can't then use a router to move this into a separate file.
Okay, so posting this solution up for my own future reference and in case somebody else stumbles into this problem.
After speaking with the express devs, it turns out that this is indeed possible with a combination of the following:
// you need to use comma separated routes
app.use(
dynamic('./server/index'),
dynamic('./server/foo')
);
// require the library at runtime and apply the req, res, next arguments
function dynamic(lib) {
return function (req, res, next) {
return require(lib).apply(this, arguments)
}
}
In the case of webpack, this would break it as you can't use require as an expression. So use the following to get around that:
function createRoutes(router) {
const dynamic = (lib) => {
return function (req, res, next) {
// let webpack generate a regex expression from this require
// if we don't you would get a critical dependency warning
// which would result in the routes not being found
return require("./src/" + lib + ".js").apply(this, arguments);
}
}
router.use(
dynamic('index'),
dynamic('foo'),
);
return router;
}
Let's step back a bit and talk about middleware.
Say you have a function which runs some kind of middleware.
const runMiddleware = (req, res, next) => {
console.log(`this will run everytime a HTTP request comes in`);
}
Then to use that middleware within express:
app.use(runMiddleware);
Every time any (GET, POST, DELETE, etc) request comes in, this function is run.
Essentially you are doing the same thing below - You are wrapping three (3) route calls with a single function. This function is calling all of these routes at once, hence res is actually being sent 3 times in a row in the example below:
app.use(function (req, res, next) { // runs every time any request comes in
require('./server/index')(req, res, next); // res sent, ok
require('./server/foo')(req, res, next); // res sent, err
require('./server/catch-all')(req, res, next); // res sent, err
});
Here is a basic way of handling routes:
const index = require('./server/index');
const foo = require('./server/foo');
app.use('/', index);
app.use('/foo', foo);
// catch everything else
app.use(function (req, res) {
res.send('catch all');
})
So I got two files my main file
file app.js
var products_id = require('./routes/productId');
app.use('/allProducts/:id',products_id);
and my route file `productId.js``where I am making a request :
router.get('/', function(req, res, next) {}
which I want to access to the parameter that the user pass /allProducts/:id/
You might try moving the parameter placeholder out of app.use('/allProducts/:id') (within app.js) and into your router definition (within productId.js).
With that done you'll have:
app.use('/allProducts', products_id) in app.js
and router.get('/:id', function(req, res, next){...}) in productId.js.
Then you should have access via req.params.id
If I understood correctly and you wamt to get the parameters on the server passed through express, see here:
How to get GET (query string) variables in Express.js on Node.js?
Try to check the req object when you enter this route
router.get('/', function(req, res, next){
console.log(req.query.id);
});
You'll find what you want from here :)
I'm new to javascript. I'm trying to make a RESTfull API using Node.js and Express.js
My directory structure is as follows
/server.js
/api/api.js
/api/location/location.js
I want to make the API modular. I want that all the requests (get/post/delete/push) beginning with /api/* to be handled by api.js and whatever routing be required, api.js should route it to proper module.
For example, if someone requests GET /api/location/abc/xyz then api.js will transfer control to location.js which will then transfer to abc.js which will finally transfer to xyz.js stored in directory /api/location/abc/xyz/xyz.js
How can I achieve this?
Code so far:
/server.js
var express = require('express');
var app = express();
var api = require('./api/api.js');
var location = require('./api/location/location.js');
//app.use('/api/location', location); //This works, but I want api.js to handle sub-routes!
app.use('/api', api);
app.get('/', function(req, res){
res.end('successful get/');
});
app.listen(12345);
/api/api.js
module.exports = function(req, res, next) {
res.end('successful get /api');
next();
};
//Add code to handle GET /api/location
/api/location/location.js
module.exports = function(req, res, next){
res.end('from location!');
next();
}
You would use express.Router([options]).
And write it that way:
/api/api.js
var router = require('express').Router();
router.get('/location', require('./api/location') );
module.exports = router;
/api/api/location.js
module.exports = function(req, res, next){
res.end('from location!');
}
And don't call next(); if you ended the response. You only call next() in your callback if you don't handle the response.
I don't know how complex your REST api will be later. But try to to keep the routing in a small number of file. Having a callback for the routing in an own file like /api/api/location.js is most likely not the best idea.
Having a rough time adding Socket.io in my Express 4 Routes. In my routes/index.js I have:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/message', function(req, res) {
console.log("Post request hit.");
// res.contentType('text/xml');
console.log(appjs);
io.sockets.emit("display text", req);
// res.send('<Response><Sms>'+req.body+'</Sms></Response>');
});
module.exports = router;
but io is undefined. I have seen several examples of how to do this, but none that worked for me. Any help would be appreciated.
You need to pass your socket.io variable to the router module so that it has access. You could do this by wrapping your module in a function call.
var express = require('express');
var router = express.Router();
/* GET home page. */
var returnRouter = function(io) {
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Express'
});
});
router.post('/message', function(req, res) {
console.log("Post request hit.");
// res.contentType('text/xml');
console.log(appjs);
io.sockets.emit("display text", req);
// res.send('<Response><Sms>'+req.body+'</Sms></Response>');
});
return router;
}
module.exports = returnRouter;
Then, whever you import this route you would call this function like: require(./routefile)(io)
Here's a good article about creating modules that require being passed a variable: Node.Js, Require and Exports
How about exploiting events? This could add an extra layer of self-awareness to the app, including socket messaging.
Since express's app() inherits from node's eventEmitter, I app.emit('EVENT_NAME', payload) at any point in my route handlers,
and then just handle that with app.on('EVENT_NAME', function(payload){})
with any logic available. I'm using it in my current setup.
This is super old, but I was looking to do the same thing and didn't find a suitable answer. I came up with a good solution using app.set('socketio', io) and req.app.get('socketio') in my route. I was then able to create a reference to the sender's socket in my route without using io.on().
See the answer I added here for the code:
Use socket.io inside a express routes file