import { parse } from 'query-string' import { getCookie } from './util' export default () => { return function () { this.headers = {} // 请求头 Authorization 计算得出 不列入其中 const headerKeys = ['sdp-app-id', 'sdp-biz-type', 'sdp-org-id', 'Accept-Language'] const alias = { 'sdp-app-id': ['appId', '__app_id'], 'Accept-Language': ['language', 'lang', 'locale', '__lang'] } const headers = {} // 初始化 从 url localStorage window.SDP_APP_DATA cookie 浏览器 中取值 const searchParams = parse(window.location.search) const hashParams = parse(window.location.hash.replace(/^#[^?]+/, '')) const db = JSON.parse(localStorage.getItem('SDP_APP_DATA') || '{}') const global = window['SDP_APP_DATA'] || {} const dataSources = [searchParams, hashParams, db, global] dataSources.forEach(data => { headerKeys.forEach(key => { if (!headers[key]) { if (data[key]) { headers[key] = data[key] } else { const aliasKeys = alias[key] || [] aliasKeys.some(aliasKey => { const value = data[aliasKey] if (value) { headers[key] = value return true } return false }) } } }) }) // 获取语言 if (!headers['Accept-Language']) { const lang = getCookie('language') || getCookie('lang') || getCookie('locale') || getCookie('__lang') || navigator.language || navigator['browserLanguage'] headers['Accept-Language'] = lang } this.data.set('headers', headers) // 有 key 返回对应的值,否则返回全部 this.headers.get = (key?: string) => { if (key) { return this.data.get('headers')[key] } else { return this.data.get('headers') } } // 设置 key value this.headers.set = (key: string, value: string) => { this.data.set('headers', Object.assign({}, this.data.get('headers'), { [key]: value })) } } }