How vue+axios implements request interception function
This time I will show you how vue axios implements the request interception function. What are the precautions for vue axios to implement the request interception function. The following is a practical case, let's take a look.
axios Introduction
axios is a Promise-based HTTP client for browsers and nodejs. It has the following characteristics:
Create XMLHttpRequest from the browser
Make http requests from node.js
Support Promise API
Intercept requests and responses
Convert request and response data
Cancel requests
Automatically Convert JSON data
Client supports preventing CSRF/XSRF
The following code introduces vue axios request interception. The specific code is as follows:
import axios from 'axios';//引入axios依赖 import { Message } from 'element-ui'; import Cookies from 'js-cookie'; //引入cookie操作依赖 import router from '@/router/index'//引入路由对象 axios.defaults.timeout = 5000; axios.defaults.baseURL =''; //http request 封装请求头拦截器 axios.interceptors.request.use( config => { var token = '' if(typeof Cookies.get('user') === 'undefined'){ //此时为空 }else { token = JSON.parse(Cookies.get('user')).token }//注意使用的时候需要引入cookie方法,推荐js-cookie config.data = JSON.stringify(config.data); config.headers = { 'Content-Type':'application/json' } if(token != ''){ config.headers.token = token; } return config; }, error => { return Promise.reject(err); } ); //http response 封装后台返回拦截器 axios.interceptors.response.use( response => { //当返回信息为未登录或者登录失效的时候重定向为登录页面 if(response.data.code == 'W_100004' || response.data.message == '用户未登录或登录超时,请登录!'){ router.push({ path:"/", querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转 }) } return response; }, error => { return Promise.reject(error) } ) /** * 封装get方法 * @param url * @param data * @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) }) }) } /** * 封装导出Excal文件请求 * @param url * @param data * @returns {Promise} */ export function exportExcel(url,data = {}){ return new Promise((resolve,reject) => { axios({ method: 'post', url: url, // 请求地址 data: data, // 参数 responseType: 'blob' // 表明返回服务器返回的数据类型 }) .then(response => { resolve(response.data); let blob = new Blob([response.data], {type: "application/vnd.ms-excel"}); let fileName = "订单列表_"+Date.parse(new Date())+".xls" ; if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, fileName); } else { var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); window.URL.revokeObjectURL(link.href); } },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) }) }) }
I believe you have mastered it after reading the case in this article For more exciting methods, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Vue implements search list content
##Detailed explanation of the steps to upload images in the vue axios form
The above is the detailed content of How vue+axios implements request interception function. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Vue is a popular JavaScript framework for building modern web applications. When developing applications using Vue, you often need to interact with different APIs, which are often located on different servers. Due to cross-domain security policy restrictions, when a Vue application is running on one domain name, it cannot communicate directly with the API on another domain name. This article will introduce several methods for making cross-domain requests in Vue. 1. Use a proxy A common cross-domain solution is to use a proxy

Kuaishou is a popular short video social platform that allows users to easily connect with others. Over time, users' private messages may be filled with a large number of strangers' messages, which may affect the user's experience. So, how to delete private messages from strangers on Kuaishou? This article will introduce in detail how to delete private messages from strangers on the Kuaishou platform, and whether it is possible to intercept messages from strangers. 1. How to delete all strangers’ messages in Kuaishou private messages? 1. First, open Kuaishou APP and enter the personal center. 2. On the personal center page, find the "Message" option and click to enter. 3. On the message page, find the "Private Message" option and click to enter. 4. On the private message page, you can see different message categories. Find the "Stranger Messages" category and click

How to block advertising pop-ups in QQ browser? Recently, sometimes when I use the computer, I often encounter the phenomenon of advertising pop-ups in the QQ browser. Like what I encountered is the QQ browser pop-up advertising, so when I encounter this kind of QQ browser pop-up advertising How to solve it? Let’s take a look with the editor of this site to see how to block advertising pop-ups in QQ browser. Tutorial to solve QQ browser pop-up ads 1. First open QQ browser, enter the main interface, and click the menu in the upper right corner. 2. After clicking on the menu of QQ Browser, you will see an application center, and then click on it. 3. After entering the QQ Browser Application Center, an extension store will pop up. 4. Install the QQ browser plug-in to block advertising pop-ups. 5. Click Install Now. 6. Install it into

How to use context to implement request retry strategy in Go Introduction: When building a distributed system, network requests will inevitably encounter some failures. In order to ensure the reliability and stability of the system, we usually use a retry strategy to handle these failed requests to increase the success rate of the request. In the Go language, we can use the context package to implement the request retry strategy. This article will introduce how to use the context package in Go to implement a request retry strategy, with code examples. 1. What is

Nginx is a lightweight, high-performance web server that not only supports advanced functions such as reverse proxy and load balancing, but also has powerful request rewriting capabilities. In actual web applications, in many cases the request URL needs to be rewritten to achieve better user experience and search engine optimization effects. This article will introduce how Nginx implements request rewriting configuration based on the request URL, including specific code examples. Rewrite syntax In Nginx, you can use the rewrite directive to perform request rewriting. its basic language

Common application scenarios of the Head request method in Laravel In Laravel, the HEAD method in the HTTP request method is usually used to obtain the metadata of the resource without obtaining the actual content. The HEAD request is similar to the GET request, but does not return the actual response body content, only the response header information. This makes the HEAD request very useful in some specific scenarios. The following are some common application scenarios and corresponding code examples. Verify the validity of the link using the HEAD request method can be used to verify the chain

How to use the Hyperf framework for request retry. With the unpredictability of network communication, we often encounter request failures in application development. In order to ensure the stability and robustness of the application, we can increase the success rate of requests through the request retry mechanism. In the Hyperf framework, we can use the Retry component provided by Hyperf to implement the request retry function. This article will introduce in detail how to use the Retry component in the Hyperf framework and give specific code examples. First, we need to

How to use context to implement request idempotence in Go Introduction In web development, idempotence is a very important concept. It ensures that multiple executions of a request do not have inconsistent side effects on the system. When dealing with concurrent requests or when the network is unstable, using idempotence can ensure the security and reliability of requests. The context package in Go provides a mechanism to handle this situation. What is idempotence? Simply put, idempotence refers to the result of multiple executions of the same operation being the same as the result of one execution.
