How can I get the browser language in node.js (express.js)?

前端 未结 4 1336
执笔经年
执笔经年 2020-12-08 02:16

User requests some page and I want to know (on server side) what is the language in his/her browser. So I could render template with the right messages.

On clie

4条回答
  •  情书的邮戳
    2020-12-08 03:00

    You would need to parse the string in req.headers["accept-language"]. Which will give you a priority list of preferred languages from the client. You can also check req.acceptsLanguages(lang [, ...]) if your language is supported or not.

    I would strongly recommend to use express-request-language to do any language matching work, since it could be very difficult to get it right at the first time.

    Most of the time, matching a language is not enough. A user might want to change a preferred language. express-request-language help you store a preferred language in a cookie it also gives your server a URL path to change a preferred language.

    All above functionality can be done with just a couple of lines of code:

    app.use(requestLanguage({
      languages: ['en-US', 'zh-CN'],
      cookie: {
        name: 'language',
        options: { maxAge: 24*3600*1000 },
        url: '/languages/{language}'
      }
    }));
    

    In case of no match, the middleware will also match a default language (en-US above).

提交回复
热议问题