需求

HTTP 协议中的 Authorization 请求 header 会包含服务器用于验证用户代理身份的凭证,通常会在服务器返回 401 Unauthorized 状态码以及 WWW-Authenticate 消息头之后在后续请求中发送此消息头。
axios 库也允许你在请求配置中配置 auth 属性,auth 是一个对象结构,包含 username 和 password 2 个属性。一旦用户在请求的时候配置这俩属性,我们就会自动往 HTTP 的 请求 header 中添加 Authorization 属性,它的值为 Basic 加密串。 这里的加密串是 username:password base64 加密后的结果。

  1. /* auth */
  2. axios({
  3. method: 'post',
  4. url: 'http://localhost:8088/more/auth',
  5. auth: {
  6. user: "admin",
  7. password: '123'
  8. },
  9. data: {
  10. isLogin: true
  11. }
  12. }).then(res => {
  13. console.log(res)
  14. })

代码实现

类型声明

export interface AxiosRequestConfig {
  // ...
  auth?: AxiosBasicCredential
}
export interface AxiosBasicCredential {
  user: string
  password: string
}

修改配置合并策略字段

const deepMergeValueKeys = ['headers', 'auth']

添加headers属性

  if (auth) {
    const { user, password } = auth
    // btoa: 字符串--->base64
    headers['authorization'] = `Basic ` + btoa(`${username}:${password}`)
  }

编写demo

添加接口路由

router.post('/more/auth', function(req, res) {
  const auth = req.headers.authorization
  console.log(auth)
  if (auth) {
    const [type, credentials] = auth.split(' ')
    if (credentials) {
      const [username, password] = atob(credentials).split(':')
      if (type === 'Basic' && username === 'admin' && password === '123') {
        res.json(req.body)
      } else {
        res.end('UnAuthorization')
      }
    }
  }

  res.json(req.data)
})