UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Express】Accept-Languagesを取得する

Expressで Accept-Languageヘッダーを取得したい

調べたところ、単純にreq.headers["accept-language"]とすれば取得できるが、調べる過程でreq.acceptedLanguagesというメソッドを知った

expressjs.com

req.acceptsLanguages(lang [, ...])
Returns the first accepted language of the specified languages, based on the request’s Accept-Language HTTP header field. If none of the specified languages is accepted, returns false. For more information, or if you have issues or concerns, see accepts.

次のように使う

var express = require('express');
app.get('/translation', function(request, response) {
    var lang = request.acceptsLanguages('fr', 'es', 'en');
    if (lang) {
        console.log('The first accepted of [fr, es, en] is: ' + lang);
        ...
    } else {
        console.log('None of [fr, es, en] is accepted');
        ...
    }
});

指定された言語のうち最初にacceptされた言語を返し、指定された言語のいずれもacceptでない場合は falseを返す

また、accepts(request).languages()を使っても最初にacceptされた言語を返し、acceptでない場合は falseを返す

var express = require('express'), accepts = require('accepts');
app.get('/translation', function(request, response) {
    console.log(accepts(request).languages());
    ...
});

github.com

参考

stackoverflow.com