Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept-Language与多语言 #30

Open
yizihan opened this issue Jun 26, 2018 · 0 comments
Open

Accept-Language与多语言 #30

yizihan opened this issue Jun 26, 2018 · 0 comments

Comments

@yizihan
Copy link
Owner

yizihan commented Jun 26, 2018

在请求头中设置 Accept-Language 浏览器接收的语言类型

多语言用之间用 , 隔开,而且每种语言有用 ; 分隔,分隔的前面为该语言的简称,后面为其权重。

将Accept-Language解析成一个数组,并按照权重进行排序。

方案一:使用Ajax发送请求

<script>
  let ajax = new XMLHttpRequest()
  ajax.open('get', 'http://localhost:8888/')
  ajax.setRequestHeader("Accept-Language","en");
  ajax.send()
  ajax.onreadystatechange = function () {
    if (ajax.readyState === 4 && ajax.status === 200) {
      document.write(ajax.responseText)
    }
  }
</script>

方案二:使用Fetch发送请求

<script>
  let myInit = {
    headers: {
      'Accept-Language': 'en'
    },
    method: 'GET'
  }
  fetch('http://localhost:8888/', myInit)
    .then(res => {
      // 这里拿到的 res 并不是后端返回的JS对象
      // 将 res.body 通过 JSON.parse 转换为JS对象
      return res.json()
    })
    .then(data => {
      // 这里 data 才是后端返回的JS对象
      document.write(data.txt)
    })
</script>

使用Express创建测试服务器

let express = require('express')
let app = express()
let port = 8888
let langPack = {
  "zh-CN": {
    txt: '你好 世界!'
  },
  "en": {
    txt: 'Hello World!'
  }
}

app.get('/', (req, res) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.send(getLang(req))
})

app.listen(port, () => {
  console.log('Listening ' + port)
})

function getLang (req) {
  // Accept-Language 字符串
  let acceptLanguage = req.headers['accept-language']
    // 将字符串转为数组
    ,langs = acceptLanguage.split(',')
    // 默认值
    ,langType = 'en'

  // 将数组继续拆分
  // ['zh-CN', 'zh;q=0.9'] => [{langType: 'zh-CN', q: 1}, {langType: 'zh', q: 0.8}]
  langs = langs.map(lang => {
    let [langType, langQ] = lang.split(';')
    let q = langQ ? parseFloat(langQ.split('=')[1]) : 1
    lang = {langType, q}
    return lang
  })
  // 数组排序 通过数组内的对象的“q”的属性值大小进行排序
  langs.sort((a, b) => b.q - a.q)
  // 遍历语言包
  for (let i=0; i<langs.length; i++) {
    let curType = langs[i].langType
    if (langPack[curType]) {
      langType = curType
      break
    }
  }
  // 返回选定的语言包
  return langPack[langType]
}

参考文章:
Accept-Language 与多语言网站应用
fetch body里数据为 ReadableStream 解决办法

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant