Suppose I have two routes defined like the following.
The first route is always executed, but the second one is not.
How should I define the routes, so that requests for /about.. are properly routed?
// First route
router.get('/:id', function (req, res) {
// This will always be executed
})
// Second route
router.get('/about/:name', function (req, res) {
// This will not be executed
})
Reverse the order
The routes are stored in a sequence in the order of your router.get() function calls. That is the order the routes are tested for a matching pattern. When you have a route that matches potentially everything, like an /:Id route, then you want to place it last. You then place the static non-changing ancillary pages before it.
In the example below I reverse the order so my static less specific route of "/about/" is checked first and if there is no match then express will compare the request to the next route for a URL match.
// Executed if match is found
router.get('/about/:name', function (req, res) {
})
// No match found on the above routes so try this one
router.get('/:id', function (req, res) {
})
//TODO: Good place for 404 handler...
Related
const express = require('express');
const app = express();
app.use('/', (req, res, next) => {
console.log('This always runs!');
next();
});
app.use('/add-product', (req, res, next) => {
console.log('In add product middleware!');
res.send('<h1>The "Add Product" Page</h1>');
});
app.use('/', (req, res, next) => {
console.log('In another middleware!');
res.send('<h1>Hello from Express!</h1>');
});
app.listen(3000);
NodeJS / Express: what is "app.use"?
I read from this post and still confused about how the flow-of-control goes in this program.How come if I visit "localhost:3000/add-product" the result logged is "This always runs!In add product middleware!This always runs!In another middleware!"(I omitted the changeline)
Does this mean after it goes into the second app.use,and as I've learnt,each app.use(middleware) is called every time a request is sent to the server.So this process restarts,but why this time next() would result in the third app.use being called?I thought next would go into the next matching path..
The order of route is important in express
Express match route based on first come first serve basis, just like a queue.
If a route matches, then whatever function you pass as callback will get called.
In your case:
Route 1: Match every route
Route 2: Match /add-product
Route 3: Match every route
So the order of checking would be 1 -> 2 -> 3
So if I make GET CALL TO /add-product
(1) and (2) will be called
and the following log
This always runs!
In add product middleware!
While call to / will
result in (1) and (3) being called.
This always runs!
In another middleware!
Next() is just passing the control to the next middleware
I m using express to make a server.
app.get("/*", (req, res) => {
res.sendFile("index.html");
});
For every endpoint, I serve the same HTML. I handle the routes on the client-side.
How do I make an endpoint such that it doesn't server "index.html".
I tried adding
app.get("/abc", (req, res) => {
res.json(some data);
});
But it sends the index.html file
Express basically checks if the requested route matches the ones you've specified (from top to bottom). If it does, it follows the given instructions. The very first route you've specified is /* which means it will match any GET request that the user asks for. Since it has found a match, it will not proceed to check the other routs. So instead, you want to specify a route like this at the very end so that it checks the other routs first.
app.get("/abc", (req, res) => {
res.json({"key": "value"});
});
/*
This route has to be placed at the end
(just before the listener)
*/
app.get("/*", (req, res) => {
res.sendFile("index.html");
});
I have this express.js code:
app.get('/', (req, res) => {
res.render('homePage', { title: 'Express' });
});
app.use((req, res) => {
console.log('use() is executed');
res.end();
});
If the request is handled by the get() method, use() is not supposed to execute. But I noticed that it still execute even though everything was fine and the page is rendered. Did I do something wrong or did I miss something? Thanks.
From Express Doc:
Link: http://expressjs.com/en/4x/api.html#app.use
app.use([path,] callback [, callback...])
Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches the path.
app.use() register the function as middleware, and you didn't specify the path. That's why it will run every time when any route is called.
The placement of the middlewares will change the execution order. However, they don't change the fact that the middleware will be executed as, well middlewares, which will be executed before the actual functions with in the routes.
All:
I am new to Express 4 router.
When I tried some login/signup example, I got one question about the .use and .get/.post function:
I saw sometimes it uses:
var express = require('express');
var router = express.Router();
router.get('/hello', function(req, res, next) {
res.send("Welcome");
});
and in main app, we use it like:
app.use("/", router);
While some other time, it uses:
var express = require('express');
var router = express.Router();
//here the router uses .use() function rather than .get/.post
router.use('/hello', function(req, res, next) {
res.send("Welcome");
});
and in main app, we use it like:
app.use("/", router);
So I am wondering what is the difference between them, does the .use() just a general name for all of get/post/put/... together?
I find this post: Difference between app.use and app.get in express.js
But still not feel easy to understand this....
Thanks
In addition to what Jonathan Lonowski said in the posted link, it might help to not compare use to get and post, but to compare it to all because both all and use work regardless of the HTTP verb used while that's obviously not true for get. Everything I'm about to say applies if you replace "all" with "get", it'll just narrow that handler down to a specific HTTP verb.
So, what's the difference between all and use?
app.all will handle incoming requests at the specified URL path regardless of the HTTP verb, just as app.use does. However, how it compares the requested URL to the handler is different. For example:
var r = express.Router();
r.use('/foo', function (...) { ... }); // Route A
r.all('/bar', function (...) { ... }); // Route B
If you make a request to /foo/123 Route A will be run.
If you make a request, however, to /bar/123 Route B will NOT be run.
This is because with HTTP verbs express compares the full path, but with 'use' it only cares about the beginning of the url. Because the URL /foo/123 begins with /foo Route A will run, but because /bar/123 does not match the FULL URL, Route B will not be. Note: You could make .all behave in the same way: r.all('/bar/*', ...), but use is easier and more appropriate for this.
So, what you would tend to mount with one vs the other is different. For example:
var app = express();
var router1 = express.Router();
var router2 = express.Router();
router2.all('*', function (req, res) { ... }); // Must specify a path!
router1.use('/secondary-routes', router2); // Can't do this with all.
app.use(router1); // Look Ma, no path!
Here I've used all to handle a request coming in, where I've used use to mount an entire router. Also, note that the usage of router.METHOD functions require a URL string as the first parameter, while use does not.
At the end of the day, if you:
Want all requests that come in under a given path (or even every request) to use the specified middleware, or
Want to mount an entire sub router/application, or
Want to include a plugin into your application
... Then use is probably what you want.
If you:
Are handling a specific request at a specific URL path (i.e. probably not doing a * match in the URL)
Generally won't be calling next and will instead actually be handling the request
... Then an HTTP verb method (like get, post or all) is probably what you want.
.use is used in 2 cases, middlewares and "modular mountable route handlers".
In your example
router.use('/hello', function(req, res, next) {
res.send("Welcome");
});
This means that any requests sent to /hello will be terminated with "Welcome" and the actual .get attached to /hello will not be called.
So, in short, call use when you need to apply some general middlewares or want to do modular architecture with routers. use can be "used" as request handlers, but you shouldn't because it is not designed for that purpose
I'm using a expressjs 4.x to build a simple api on top of mongodb.
The api needs to serve a few sets of data:
/api/v1/datatype1
/api/v1/datatype2
For each data type, I have CRUD operations (post, get, put, delete).
The api requests would look like this:
POST /api/v1/datatype1
GET /api/v1/datatype1:_id
PUT /api/v1/datatype1:_id
DELETE /api/v1/datatype1:_id
If I create a router params like this:
dataType1ApiRouter.param("entity_id", function (req, res, next, id) {
//async db fetch here by id, then call next with fetched data
//or error if faild request/not found entity.
//let's say req.dataEntity = dataEtity; next();
} );
If I create a route like this:
dataType1ApiRouter.route("/datatype1")
.get(":entity_id", function (req, res, next) {
//expcet req.dataEntity to be fetched by the param filter.
})
.post(function(req, res, next) {
//just create an new dataType1 entity.
});
I am getting a syntax error. The route .get and .post (and other methods like those) expect just one parameter, resulting in an error:
Route.get() requires callback functions but got a [object String]
Is there a way to actually group all the "/datatype1" requests under one url declaration instead of repeating the method("datatype1:entity_id") for each method that requires the ID expect for the post method?
There isn't a clean way to do this with Router.route(), but you might consider doing this with another Router instead of a Route there. Then, you could just mount that sub-router.
Basic example, modifying the code you provided:
var mainRouter = express.Router(),
subrouter = express.Router();
subrouter.param("entity_id", function (req, res, next, id) {
// param handler attached to subrouter
});
subrouter.post('/', function(req, res, next) {
// post handler attached to base mount-point
});
subrouter.get("/:entity_id", function (req, res, next) {
// get handler attached to base mount-point/<id>
});
// here we mount the sub-router at /datatype1 on the other router
mainRouter.use('/datatype1', subrouter);
Note that this requires adding a '/' to the URL, so instead of /api/v1/datatype1[someidhere] it would be /api/v1/datatype1/someidhere