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

How to implement ajax request using axios (detailed tutorial)

Jun 19, 2018 pm 04:09 PM
ajax ajax request axios vue

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'
}
Copy after login

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: '用户名或者密码错误'
  }
 }
 ]
}
Copy after login

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
Copy after login

4. Use

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

## 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
Copy after login

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'
Copy after login

The premise of writing like this is to write

export var login = api.login
Copy after 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 of this Website
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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use echarts in vue How to use echarts in vue May 09, 2024 pm 04:24 PM

How to use echarts in vue

The role of export default in vue The role of export default in vue May 09, 2024 pm 06:48 PM

The role of export default in vue

How to use map function in vue How to use map function in vue May 09, 2024 pm 06:54 PM

How to use map function in vue

The difference between export and export default in vue The difference between export and export default in vue May 08, 2024 pm 05:27 PM

The difference between export and export default in vue

The role of onmounted in vue The role of onmounted in vue May 09, 2024 pm 02:51 PM

The role of onmounted in vue

Onmounted in vue corresponds to which life cycle of react Onmounted in vue corresponds to which life cycle of react May 09, 2024 pm 01:42 PM

Onmounted in vue corresponds to which life cycle of react

What are hooks in vue What are hooks in vue May 09, 2024 pm 06:33 PM

What are hooks in vue

What scenarios can event modifiers in vue be used for? What scenarios can event modifiers in vue be used for? May 09, 2024 pm 02:33 PM

What scenarios can event modifiers in vue be used for?

See all articles