In this article, we mainly share with you the analysis of VueJs’s Axios interface request tool. Axios is an HTTP client based on Promise for browsers and nodejs. Today we will introduce VueJs to build the Axios interface request tool. Friends who need it can refer to this article. I hope it can help everyone.
axios Introduction
axios is a Promise-based HTTP client for browsers and nodejs. It has the following characteristics:
Create XMLHttpRequest from the browser
Make an http request from node.js
-
Support Promise API
Interception of requests and responses
Convert request and response data
Cancel request
Automatically convert JSON data
Client support prevents CSRF/XSRF
In the previous chapter, we learned about the directory structure of the project, made some adjustments to the directory structure of the project, and were able to get the project running again. Today we will build the API interface calling tool Axios. Vue itself does not support ajax calls. If you need these functions, you need to install the corresponding tools.
There are many tools that support ajax requests, such as superagent and axios. Today we are using axios, because I heard that most of the tutorial books on the Internet recently use axios. The axios tool itself has been well optimized and encapsulated, but it is still relatively cumbersome to use, so we will Repackage it.
Install Axios tools
##cnpm install axios -D
Encapsulating Axios tools
Edit the src/api/index.js file (when we organized the directory structure in the previous chapter, in src/ An empty index.js file is created in the api/ directory), now we fill in the content of the file.// 配置API接口地址 var root = 'https://cnodejs.org/api/v1' // 引用axios var axios = require('axios') // 自定义判断元素类型JS function toType (obj) { return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() } // 参数过滤函数 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 } /* 接口处理函数 这个函数每个项目都是不一样的,我现在调整的是适用于 https://cnodejs.org/api/v1 的接口,如果是其他接口 需要根据接口的参数进行调整。参考说明文档地址: https://cnodejs.org/topic/5378720ed6e2d16149fa16bd 主要是,不同的接口的成功标识和失败提示是不一致的。 另外,不同的项目的处理方法也是不一致的,这里出错就是简单的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) } }) } // 返回在vue模板中的调用接口 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) } }
Configuring the Axios tool
Before we use it, we need to configure it in src/main For simple configuration in .js, first take a 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 } })and modify it 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' // 引用API文件 import api from './api/index.js' // 将API方法绑定到全局 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 the project. Next, let's test this tool.
Using Axios tools
Let’s modify the src/page/Index.vue file and adjust the code to the following code:
<template> <p>index page</p> </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 console in Index.vue. If you are the same as me, it means that our interface configuration is complete. correct. As shown below:
Vuejs uses vue-markdown to render comment methods
Summary of knowledge about Vuejs technology stack
Comprehensive analysis of VueJS
The above is the detailed content of Analysis on VueJs to build Axios interface request tool. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version
Chinese version, very easy to use
