Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional extension in expressjs route

I want to have an optional extension, like .xml or .csv or .json (the default, no extensions would return json).

app.get('/days-ago/:days(.:ext)?', function(req, res) {

This doesn't appear to work, is there anything I'm doing wrong?

GET /days-ago/7.xml
GET /days-ago/7.csv
GET /days-ago/7.json
GET /days-ago/7
like image 345
chovy Avatar asked Jan 05 '15 02:01

chovy


People also ask

What is return next (); in Express?

app. use((req, res, next) => { //next() or return next() }); In the function app. use((req, res, next), we have three callbacks i.e. request, response and next. So, if you want to use next() then simply write next() and if you want to use return next then simply write return next().

How many middleware can be on a single route?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app.

How does Middlewares work in Express?

Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

How the dynamic routing is working in Expressjs?

To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them. var express = require('express'); var app = express(); app. get('/:id', function(req, res){ res.


1 Answers

It seems that you are using wrong pattern for the route. Here is the corrected one:

app.get('/days-ago/:days\.:ext?', function(req, res) {

Therefore, to achieve your goal I would create a middleware that checks for the empty parameter and sets it to the desired one

Something like this:

var defaultParamMiddleware = function(req, res, next) {
    if (!req.params.ext) {
        req.params.ext = 'json';
    }

    next();
};

app.get('/days-ago/:days\.:ext?', defaultParamMiddleware, function (req, res) {
    res.json(req.params);
});
like image 116
Vitalii Zurian Avatar answered Nov 15 '22 10:11

Vitalii Zurian