Search code examples
node.jsexpressmiddleware

How to handle req parameters in Middleware function


I want to handle request parameter in middleware function in expressjs framework. To describe my problem I created very small working example. Let's consider I want to have a language parameter in the path and change its value to default if the given value is wrong (not supported language). Let's assume I only support 'en' and 'fi' languages and I want to set the "lang" parameter to 'fi' if user given anything else than ['en', 'fi'].

To do that I prepared a below piece of code:

const express = require('express');
const app = express();

// MIDDLEWARE FUNTION
function handleLang(req, res, next) {
    console.log("from handleLang I see params: "); console.log(req.params)
    var supportedLangs = ['en', 'fi']
    if (req.params.lang === undefined || (supportedLangs.indexOf(req.params.lang) == -1)) {
        console.log("so changing req.params.lang to default...")
        req.params.lang = "fi"
        console.log("before I leave handleLang I see req.params as: "); console.log(req.params)
    }
    return next()
}

app.use("/:lang*?", handleLang)

app.get('/:lang*?', function (req, res) {
    console.log('from app.get I see following params: '); console.log(req.params)
    res.send('index')
})

app.listen(4000, () => {
    console.log('Server started....')
})

I expected that the the handleLang function will change the lang to default value and I will see that in get function. Unfortunately I was wrong.

When I go to address http://localhost:4000/xx, I see following output:

Server started....
from handleLang I see params:
{ '0': '', lang: 'xx' }
so changing req.params.lang to default...
before I leave handleLang I see req.params as:
{ '0': '', lang: 'fi' }
from app.get I see following params:
{ '0': '', lang: 'xx' }
from handleLang I see params:
{ '0': '', lang: 'favicon.ico' }
so changing req.params.lang to default...
before I leave handleLang I see req.params as:
{ '0': '', lang: 'fi' }
from app.get I see following params:
{ '0': '', lang: 'favicon.ico' }

I have no idea why req.params.lang somehow changes to 'favicon.ico' and I don't understand why I see the same message twice. Can anyone explain me why it happens and describe how it should be done properly?


Solution

  • One approach can be that you can set the language inside middleware like below:

    `req.headers['language'] = 'fi';`
    

    You can later access this value like below:

    console.log(req.headers['language'])