How to get optional language parameter from URL in Express routes?

旧街凉风 提交于 2019-12-10 10:33:24

问题


I'm stuck with a stupid problem: How to work with optional locale parameter?

That's what I mean:

For example, I have frontpage and contacts, here is routes:

app.get('/', frontpage.get);
app.get('/contacts', contacts.get);

Now I'm trying to add localization to my site

app.all('/:lang?*', language.all); -> detect and set locale
app.get('/:lang?', frontpage.get);
app.get('/:lang?/contacts', contacts.get);

The only problem is when I don't use lang-parameter in URL:

mysite.com/contacts

because Express uses 'contacts' as a language parameter. (+ I don't like this copy-pasted :lang?)

I think, I just took the wrong way.

How to use locale parameter from URL in Express?

PS: I dont want to use subdomains de.mysite.com or querystring mysite.com?lang=de. I want exactly this variant mysite.com/de


回答1:


Most modules use Accept-Language so I can't find any that use the path like this that you might be able to use. So you'll need to define your own middleware that initializes before everything else. Express's Router doesn't really help for your usecase.

app.use(function(req, res, next){
    var match = req.url.match(/^\/([A-Z]{2})([\/\?].*)?$/i);
    if (match){
        req.lang = match[1];
        req.url = match[2] || '/';
    }
    next();
});

Now you can use req.lang in your routes or other middleware to configure your translation logic and since we have rewritten the URL, later logic will not know that there is a language param.



来源:https://stackoverflow.com/questions/22883014/how-to-get-optional-language-parameter-from-url-in-express-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!