Home  >  Article  >  Web Front-end  >  How to implement ajax request using axios (detailed tutorial)

How to implement ajax request using axios (detailed tutorial)

亚连
亚连Original
2018-06-19 16:09:071954browse

I previously introduced you to jQuery’s use of the most elegant way to write ajax requests. This article mainly introduces you to the relevant information about the advanced practice of axios and the use of the most elegant way to write ajax requests. The article uses examples. The code introduction is very detailed and has certain reference learning value for everyone's study or work. Friends who need it can take a look below.

Preface

I believe ajax does not need to be introduced too much. The author firmly believes that problems that can be solved with configuration should not be hard-coded. The following words will not Enough said, let’s take a look at the detailed introduction.

Sister article jQuery Advanced: Write ajax requests in the most elegant way

axios is the ajax library officially recommended by Vue, used to replace vue-resource. For more detailed basic knowledge, please refer to this article: //www.jb51.net/article/109444.htm

Advantages:

  • To add an ajax interface, you only need to write a few more lines in the configuration file

  • There is no need to write axios calls in the component, it is very convenient to directly call the api method

  • If the interface is adjusted, you only need to modify the interface configuration file

  • Unified management interface configuration

1. content-type configuration

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

2. api configuration

// 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 method

// 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 = {}
// render 函数用来渲染路径上的变量, 算是一个微型的模板渲染工具
// 例如render('/{{userId}}/{{type}}/{{query}}', {userId:1,type:2, query:3})
// 会被渲染成 /1/2/3
function render (tpl, data) {
 var re = /{{([^}]+)?}}/
 var match = ''
 while ((match = re.exec(tpl))) {
 tpl = tpl.replace(match[0], data[match[1]])
 }
 return tpl
}
// fire中的this, 会动态绑定到每个接口上
function fire (query = {}, payload = '') {
 // qs 特别处理 formData类型的数据
 if (this.contentType === contentType.formData) {
 payload = qs.stringify(payload)
 } 
 // 直接返回axios实例,方便调用then,或者catch方法
 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. Use

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

## in the component #Browser results:

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

5. More

There is something I don’t quite understand, I hope someone who understands can Give me an answer

If only the login method is needed in a certain component, but if I write like this, an error will be reported.

import {login} from '@/apis/request'

The premise of writing like this is to write

export var login = api.login

at the end of request.js. But this is what I don’t want, because every time an interface is added, it must be exported once. This is not It complies with the open-closed principle. Is there any better way?

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement gulp packaging using nodejs

Detailed interpretation of the new features of Angular5.1

How to use vuex to implement menu management

The above is the detailed content of How to implement ajax request using axios (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn