4. VueJs Pit Filling Diary Build Axios Interface Request Tool

Keywords: axios Vue Webpack JSON

In the previous chapter, we learned about the catalog structure of the project, and made some adjustments to the catalog structure of the project so that we can run the project again.Today we'll build the api interface invocation tool Axios.Vue itself does not support ajax calls, and if you need these features you need to install the appropriate tools.

There are many tools to support ajax requests, such as superagent and axios.Today we are using axios, because we have heard that most of the online tutorial books recently use axios, Axios itself has been well optimized and encapsulated, but it is still cumbersome to use, so we will re-encapsulate it.

Install Axios Tools

cnpm install axios -D

 

When installing, be sure to switch to our project root directory, run the installation command, and then prompt for the above information to indicate that the installation is complete.

 

Encapsulate Axios Tools
Edit the src/api/index.js file (we created an empty index.js file in the src/api/directory when we cleaned up the directory structure in the previous chapter), and now we'll fill it in.

// Configure API interface address
var root = 'https://cnodejs.org/api/v1'
// Reference axios
var axios = require('axios')
// Custom Judgement Element Type JS
function toType (obj) {
	return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// Parameter filter function
function filterNull (o) {
	for (var key in o) {
		if (o[key] === null) {
			delete o[key]
		}
		if (toType(o[key]) === 'string') {
			o[key] = o[key].trim()
		} else if (toType(o[key]) === 'object') {
			o[key] = filterNull(o[key])
		} else if (toType(o[key]) === 'array') {
			o[key] = filterNull(o[key])
		}
	}
	return o
}

/*
  Interface Processing Functions
  This function is different for each item, and what I'm adjusting now is that it works for
  https://cnodejs.org/api/v1 Interface, if other
  Adjustments need to be made based on the parameters of the interface.Reference Instructions Document Address:
  https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
  Mainly, the success identification and failure hints for different interfaces are inconsistent.
  In addition, different projects are treated differently, and the error here is a simple alert
*/
function apiAxios (method, url, params, success, failure) {
	if (params) {
		params = filterNull(params)
	}
	axios({
		method: method,
		url: url,
		data: method === 'POST' || method === 'PUT' ? params : null,
		params: method === 'GET' || method === 'DELETE' ? params : null,
		baseURL: root,
		withCredentials: false
	})
	.then(function (res) {
	if (res.data.success === true) {
		if (success) {
			success(res.data)
		}
	} else {
		if (failure) {
			failure(res.data)
		} else {
			window.alert('error: ' + JSON.stringify(res.data))
		}
	}
	})
	.catch(function (err) {
		let res = err.response
		if (err) {
			window.alert('api error, HTTP CODE: ' + res.status)
		}
	})
}

// Returns the calling interface in the vue template
export default {
	get: function (url, params, success, failure) {
		return apiAxios('GET', url, params, success, failure)
	},
	post: function (url, params, success, failure) {
		return apiAxios('POST', url, params, success, failure)
	},
	put: function (url, params, success, failure) {
		return apiAxios('PUT', url, params, success, failure)
	},
	delete: function (url, params, success, failure) {
		return apiAxios('DELETE', url, params, success, failure)
	}
}

For more explanations of AxIos, see: https://github.com/mzabriskie/axios

Configure Axios Tools
Before we can use it, we need to do a simple configuration in src/main.js, let's first look at the original main.js file

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
    new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: { App }
})

Modify to:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

// Reference API file
import api from './api/index.js'
// Bind API methods globally
Vue.prototype.$api = api

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: { App }
})

With the above configuration, we can use the axios tool in our project, and let's test it next.

Using the Axios tool
Let's modify the src/page/Index.vue file to adjust the code to the following:

<template>
    <div>index page</div>
</template>
<script>
export default {
    created () {
        this.$api.get('topics', null, r => {
            console.log(r)
        })
    }
}
</script>

We enter some data requested by the interface into the browser's console in Index.vue, and if you and I are the same, our interface configuration is correct.As follows:

If you follow my steps step by step, the end result should be the same as mine.If something goes wrong, check the code carefully.

Posted by doucie on Tue, 06 Aug 2019 11:25:44 -0700