axios进阶:用最优雅的方式写ajax请求

可以用配置解决的问题,请勿硬编码
姊妹篇 jQuery进阶:用最优雅的方式写ajax请求

axios是Vue官方推荐的ajax库,用来取代vue-resource。

优点:

1. content-type配置

// filename: content-type.js
module.exports = {
  formData: 'application/x-www-form-urlencoded; charset=UTF-8',json: 'application/json; charset=UTF-8'
}

2. api 配置

// filename: api-sdk-conf.js
import contentType from './content-type'

export default {
  baseURL: 'http://192.168.40.231:30412',apis: [
    {
      name: 'login',path: '/api/security/login?{{id}}',method: 'post',contentType: contentType.formData,status: {
        401: '用户名或者密码错误'
      }
    }
  ]
}

3. request.js 方法

// request.js
import axios from 'axios'
import qs from 'qs'
import contentType from '@/config/content-type'
import apiConf from '@/config/api-sdk-conf'

var api = {}

function render (tpl,data) {
  var re = /{{([^}]+)?}}/
  var match = ''

  while ((match = re.exec(tpl))) {
    tpl = tpl.replace(match[0],data[match[1]])
  }

  return tpl
}

function fire (query = {},payload = '') {
  // qs 特别处理 formData类型的数据
  if (this.contentType === contentType.formData) {
    payload = qs.stringify(payload)
  }

  return axios({
    method: this.method,url: render(this.url,query),data: payload,headers: {
      contentType: this.contentType
    }
  })
}

apiConf.apis.forEach((item) => {
  api[item.name] = {
    url: apiConf.baseURL + item.path,method: item.method,status: item.status,contentType: item.contentType,fire: fire
  }
})

export default api

4. 在组件中使用

import api from '@/apis/request'
...
      api.login.fire({id: '?heiheihei'},{
        username: 'admin',password: 'admin',namespace: '_system'
      })
...

浏览器结果:

Request URL:http://192.168.40.231:30412/api/security/login??heiheihei
Request Method:POST
Status Code:200 OK
Remote Address:192.168.40.231:30412
Referrer Policy:no-referrer-when-downgrade

POST /api/security/login??heiheihei HTTP/1.1
Host: 192.168.40.231:30412
Connection: keep-alive
Content-Length: 47
Accept: application/json,text/plain,*/*
Origin: http://localhost:8080
contentType: application/x-www-form-urlencoded; charset=UTF-8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/62.0.3202.94 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8080/
Accept-Encoding: gzip,deflate
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8

username=admin&password=admin&namespace=_system

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...