Home > Article > Web Front-end > Configuration steps for Axios (detailed tutorial)
This article mainly shares with you the configuration steps of dynamic Axios. The article introduces the sample code in very detail. Through this tutorial, you can easily realize the configuration of dynamic Axios. Friends who need it can refer to it.
Preface
When I used to write Vue projects, I used vue-resource as the project ajax library, especially on a certain day in November. An update on Weibo indicates that the ajax library should be universal, and technical support for vue-resource has been abandoned and axios is recommended.
It is recommended to use the Vue-cli tool to create and manage projects. Even if you are not familiar with it at the beginning, you will know the secrets after using it. Some time ago, the officially recommended data request plug-in was Vue-resource, but now it has changed and turned into Axios. You don’t need to know why it changed. Anyway, this one is better to use than that one, so just use it. Here are some encapsulations of axios I'm asking for some experience, and I hope you can tell me if I'm wrong!
The method is as follows
1. Create the file. After the Vue project is initialized, create a util tool folder in the src directory, usually Used to store some encapsulated function methods. Now let us create an http.js file in the util file directory to encapsulate the axios method.
2. Directly upload the code (regular version), there are detailed comments in the code
import axios from 'axios' //引用axios import {Promise} from 'es6-promise' //引入Promise // axios 配置 axios.defaults.timeout = 5000; //设置超时时间 axios.defaults.baseURL = 'http://localhost:4000/api/v1/'; //这是调用数据接口 // http request 拦截器(所有发送的请求都要从这儿过一次),通过这个,我们就可以把token传到后台,我这里是使用sessionStorage来存储token等权限信息和用户信息,若要使用cookie可以自己封装一个函数并import便可使用 axios.interceptors.request.use( config => { const token = sessionStorage.getItem("token"); //获取存储在本地的token config.data = JSON.stringify(config.data); config.headers = { 'Content-Type':'application/json' //设置跨域头部,虽然很多浏览器默认都是使用json传数据,但咱要考虑IE浏览器。 }; if (token) { config.headers.Authorization = "Token " + token; //携带权限参数 } return config; }, err => { return Promise.reject(err); } ); // http response 拦截器(所有接收到的请求都要从这儿过一次) axios.interceptors.response.use( response => { //response.status===401是我和后台约定的权限丢失或者权限不够返回的状态码,这个可以自己和后台约定,约定返回某个自定义字段也是可以的 if(response.status == 401) { router.push({ //push后面是一个参数对象,可以携带很多参数,具体可以去vue-router上查看,例如query字段表示携带的参数 path: '/login' }) } return response; }, error => { return Promise.reject(error.response.data) }); export default axios; /** * fetch 请求方法 * @param url * @param params * @returns {Promise} */ export function fetch(url, params = {}) { return new Promise((resolve, reject) => { axios.get(url, { params: params }) .then(response => { resolve(response.data); }) .catch(err => { reject(err) }) }) } /** * post 请求方法 * @param url * @param data * @returns {Promise} */ export function post(url, data = {}) { return new Promise((resolve, reject) => { axios.post(url, data) .then(response => { resolve(response.data); }, err => { reject(err); }) }) } /** * patch 方法封装 * @param url * @param data * @returns {Promise} */ export function patch(url, data = {}) { return new Promise((resolve, reject) => { axios.patch(url, data) .then(response => { resolve(response.data); }, err => { reject(err); }) }) } /** * put 方法封装 * @param url * @param data * @returns {Promise} */ export function put(url, data = {}) { return new Promise((resolve, reject) => { axios.put(url, data) .then(response => { resolve(response.data); }, err => { reject(err); }) }) }
3. (Dynamic version), the axios interceptor is not necessary, not every project requires it , and there is more than one Content-Type and Authorization in the headers, so another method needs to be used.
util/http.js
import axios from 'axios' //引用axios import {Promise} from 'es6-promise' //引入Promise // axios 配置和拦截器都不用了,这里我使用了一个动态配置数据请求地址,在App.vue中,代码在下面,这个也不是必须的。 //^_^下面都设置一个默认的头部,使用的时候可以传入数据覆盖^_^,例如使用fetch(GET)方法时,没有请求数据,但是请求头有变化,则应写成 fetch("地址", {}, {"这里写头部的内容"}) 记住没数据用一个空对象占位置 /** * fetch 请求方法 * @param url * @param params * @returns {Promise} */ export function fetch(url, params = {}, headers = { 'Content-Type': 'application/json', //设置跨域头部 "Authorization": 'JWT ' + sessionStorage.getItem("authToken") }) { return new Promise((resolve, reject) => { axios.get(url, { params: params, headers: headers }) .then(response => { resolve(response.data); }) .catch(err => { reject(err.response) }) }) } /** * post 请求方法 * @param url * @param data * @returns {Promise} */ export function post(url, data = {}, config = { "headers": { 'Content-Type': 'application/json', //设置跨域头部 "Authorization": 'JWT ' + sessionStorage.getItem("authToken") } }) { return new Promise((resolve, reject) => { axios.post(url, data, config) .then(response => { resolve(response.data); }, err => { reject(err.response); }) }) } /** * patch 方法封装 * @param url * @param data * @returns {Promise} */ export function patch(url, data = {}, config = { "headers": { 'Content-Type': 'application/json', //设置跨域头部 "Authorization": 'JWT ' + sessionStorage.getItem("authToken") } }) { return new Promise((resolve, reject) => { axios.patch(url, data, config) .then(response => { resolve(response.data); }, err => { reject(err.response); }) }) } /** * put 方法封装 * @param url * @param data * @returns {Promise} */ export function put(url, data = {}, config = { "headers": { 'Content-Type': 'application/json', //设置跨域头部 "Authorization": 'JWT ' + sessionStorage.getItem("authToken") } }) { return new Promise((resolve, reject) => { axios.put(url, data, config) .then(response => { resolve(response.data); }, err => { reject(err.response); }) }) }
App.vue (This is the program entry file in the src directory)
<template> <p id="app"> <router-view/> </p> </template> <script> import axios from 'axios'; let protocol = window.location.protocol; //协议 let host = window.location.host; //主机 let reg = /^localhost+/; if(reg.test(host)) { //若本地项目调试使用 axios.defaults.baseURL = 'http://10.0.xx.xxx:xxxx/api/'; } else { //动态请求地址 axios.defaults.baseURL = protocol + "//" + host + "/api/"; } axios.defaults.timeout = 30000; export default { name: 'app', axios //这里记得导出,若请求地址永久固定一个,则就按照`普通版`配置一个baserURL就可以了 } </script> <style lang="scss"> //这里我使用的是scss @import '~@/style/style' </style>
Summary
FAQ
When using the dynamic version, why is it called dynamic? Because the access address and the request address are the same address and port number. For example, if I access the project through http://www.cmgos.com (default port 80), then my baseURL will automatically change to http:www.cmgos.com:80/api/. The reason for this is that one day When the project is migrated or http is changed to https, you don’t need to change the request address. The program will automatically complete it.
Is the data request address configured correctly? If you configure baseURL, then when using your encapsulated function, you only need to pass in the request address based on baseURL. For example, if you pass in login/, the request address will automatically become http:www.cmgos.com:80/api/login/ , if not configured, you can directly pass in the entire request address
Notes
When using the dynamic version, since no interceptor is used , so the function encapsulated below needs to be written as err.response.data
when returning an error to obtain the returned data, but I wrote err.response
because this can be obtained (status) status code and other information, if you do not need to judge the returned status code, just change it to err.response.data
The above is what I compiled for everyone, I hope it will be used in the future Helpful to everyone.
Related articles:
How to use the loading progress plug-in with pace.js and NProgress.js (detailed tutorial)
In the WeChat applet About the App life cycle (detailed tutorial)
In jQuery about the use of NProgress.js loading progress plug-in
In the WeChat applet How to use switch component
The above is the detailed content of Configuration steps for Axios (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!