Table of Contents
1. Global configuration of axios
2. axios interceptor
Home Web Front-end Vue.js In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

Aug 10, 2022 am 09:55 AM
axios

1. Global configuration of axios

1. Why global configuration of axios

In actual project development, almost every component will be used axios initiates a data request. At this time, you will encounter the following two problems:

① Each component needs to import axios (bloated code)

② Every time you send a request, you need to fill in the complete request path (not conducive to Later maintenance) [Related recommendations: vue.js video tutorial]

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

2. How Global configuration axios

In the main.js entry file, mount axios globally through app.config.globalProperties. The sample code is as follows:

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

3. Global configuration of axios in the vue2 project

Needs to configure axios globally through the prototype prototype object of the Vue constructor in the main.js entry file

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

2. axios interceptor

1. What is an interceptor

Interceptors (English: Interceptors) will be automatically triggered every time an ajax request is made and a response is received.

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

2. Configure request interceptor

Pass axios.interceptors.request.use(successful callback, failure callback) Request interceptors can be configured. The sample code is as follows:

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

##2.1 Request Interceptor – Token Authentication

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

2.2 Request Interceptor – Display Loading effect

With the help of Loading effect component provided by element ui

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

3. Configure the response interceptor

You can configure the response interceptor through axios.interceptors.response.use (successful callback, failed callback). The sample code is as follows:

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

A practical example showing the Loading effect:

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

3. Proxy cross-domain proxy

1. Interface cross-domain problem

Solve cross-domain problem


1), Cors (the most standard processing) does not require front-end personnel to do any processing. Only the person who writes the server needs to add a few special response headers when returning the response in the server

2), Jsonp The most An ingenious solution is to use the src attribute in the script tag to not be restricted by the same-origin policy when introducing external resources. This feature is rarely used in development because it requires front-end and back-end personnel to complete it together, and it can only solve get requests. Cross-domain issues

3), proxy server

The proxy server is also a server. Its port number is consistent with our own. The communication between the two servers does not comply with the same origin policy restrictions. That’s it. This can solve the cross-domain problem. Therefore, when sending a request, the port number is also 8080


The address where the vue project runs: http://localhost:8080/

The address where the API interface runs : http://www.escook.cn/api/users

Since the current API interface does not enable CORS cross-domain resource sharing, by default, the above interface cannot request successfully!

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

2. Solve cross-domain problems of interfaces through proxies

When projects created through vue-cli encounter cross-domain problems with interfaces, they can be solved through proxies:

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

① Set the request root path of axios to the running address of the vue project (interface requests no longer cross domain)

② vue The project finds that the requested interface does not exist, and forwards the request to the proxy agent

③ The proxy replaces the request root path with the value of the devServer.proxy attribute and initiates a real data request

④ The proxy forwards the request The received data is forwarded to axios

3. Configure proxy in the project

Step 1. In the main.js entry file, change the request root path of axios to the current web project Root path:

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

Step 2, create the vue.config.js configuration file in the project root directory , and declare the following configuration:

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

##① The proxy provided by devServer.proxy Function, only effective during the development and debugging phase

② When the project is launched online, the API interface server still needs to be enabled for CORS cross-domain resource sharing

Usage method 1 Configure the proxy server There are two imperfections :

1. Cannot flexibly control whether to use the proxy server


The public folder is equivalent to the root path of the 8080 server (what is in the 8080 server depends on the public file What is in the folder) When the requested resource 8080 itself has it, the request will not be forwarded to the 5000 server

2. Multiple proxies cannot be configured, and the request can only be forwarded to the 5000 server

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

Use method 2 to open the proxy server '/api' request prefix

Function: When a local request is sent to the proxy When using the server, the proxy server will determine whether the prefix of the request is '/api'. If it is, the request will be sent (forward the request to 5000). If not, the request will not be sent. You can flexibly control whether to use the proxy server ('/api' It is not a fixed value and can be customized as '/hah', etc.)

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

The carrying position of the prefix: immediately follows the port number

In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

If you directly request this, it will cause a 404 error because when sending the request to the 5050 server, it still carries /api/ students, the 5050 server has students but does not have /api/students


Adding this configuration can ensure that when the proxy server sends a request to the 5050 server, only /students is sent to get the data


In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

ws role: used to support websocket

changeOrigin: (used to control the value of host in the request header)

When changeOrigin: true, the proxy server will indicate that it is also a 5050 server

When changeOrigin: false, the proxy server indicates that it is an 8080 server

Sometimes the 5050 server will There are some restrictions, so this configuration item is best set to true.


If ws and changeOrigin are not written, the default value is also true (if not written as false in react)

The above is the detailed content of In-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text). 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 AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
What should I do if 'Uncaught (in promise) Error: Request failed with status code 500' occurs when using axios in a Vue application? What should I do if 'Uncaught (in promise) Error: Request failed with status code 500' occurs when using axios in a Vue application? Jun 24, 2023 pm 05:33 PM

It is very common to use axios in Vue applications. axios is a Promise-based HTTP client that can be used in browsers and Node.js. During the development process, the error message "Uncaught(inpromise)Error: Requestfailedwithstatuscode500" sometimes appears. For developers, this error message may be difficult to understand and solve. This article will explore this

Choice of data request in Vue: Axios or Fetch? Choice of data request in Vue: Axios or Fetch? Jul 17, 2023 pm 06:30 PM

Choice of data request in Vue: AxiosorFetch? In Vue development, handling data requests is a very common task. Choosing which tool to use for data requests is a question that needs to be considered. In Vue, the two most common tools are Axios and Fetch. This article will compare the pros and cons of both tools and give some sample code to help you make your choice. Axios is a Promise-based HTTP client that works in browsers and Node.

How to solve the problem of 'Error: Network Error' when using axios in Vue application? How to solve the problem of 'Error: Network Error' when using axios in Vue application? Jun 25, 2023 am 08:27 AM

How to solve the problem of "Error: NetworkError" when using axios in Vue application? In the development of Vue applications, we often use axios to make API requests or obtain data, but sometimes we encounter "Error: NetworkError" in axios requests. What should we do in this case? First of all, you need to understand what "Error:NetworkError" means. It usually means that the network connection

What should I do if 'TypeError: Failed to fetch' occurs when using axios in a Vue application? What should I do if 'TypeError: Failed to fetch' occurs when using axios in a Vue application? Jun 24, 2023 pm 11:03 PM

Recently, during the development of Vue applications, I encountered a common problem: "TypeError: Failedtofetch" error message. This problem occurs when using axios to make HTTP requests and the backend server does not respond to the request correctly. This error message usually indicates that the request cannot reach the server, possibly due to network reasons or the server not responding. What should we do after this error message appears? Here are some workarounds: Check your network connection due to

What is the parameter passing specification for Java axios and spring front-end and back-end separation? What is the parameter passing specification for Java axios and spring front-end and back-end separation? May 03, 2023 pm 09:55 PM

1. The axios parameter transfer method corresponding to the @RequestParam annotation takes the following Springjava code as an example. The interface uses the POST protocol, and the parameters that need to be accepted are tsCode, indexCols, and table. For this Spring HTTP interface, how should axios pass parameters? How many methods are there? Let’s introduce them one by one. @PostMapping("/line")publicList

Efficiently utilize Vue and Axios to implement batch processing of front-end data Efficiently utilize Vue and Axios to implement batch processing of front-end data Jul 17, 2023 pm 10:43 PM

Efficiently utilize Vue and Axios to implement batch processing of front-end data. In front-end development, data processing is a common task. When we need to process a large amount of data, processing the data will become very cumbersome and inefficient if there is no effective method. Vue is an excellent front-end framework, and Axios is a popular network request library. They can work together to implement batch processing of front-end data. This article will introduce in detail how to efficiently use Vue and Axios for batch processing of data, and provide relevant code examples.

How do the axios and SpringBoot front-ends call the back-end interface for data interaction? How do the axios and SpringBoot front-ends call the back-end interface for data interaction? May 13, 2023 am 10:34 AM

1. Introducing a complete system, front-end and back-end interaction is essential. This process can be divided into the following steps: the front-end initiates a request to the back-end. After the back-end interface receives the front-end parameters, it begins to call methods layer by layer to process the data. The back-end will The final data is returned to the front-end interface. After the front-end request is successful, the data is rendered to the interface. 2. Project structure Front-end technology: axios Back-end technology: SpringBoot (This does not matter, but you must have an access path to the control layer, which is the so-called request. The address corresponding method can use SSM framework, SSH framework, etc.) The above is the general file structure. I believe that everyone’s back-end data processing will be fine. It is nothing more than: the control layer receives the front-end request and calls the corresponding business layer interface method. layer implementation

How to use vue3+ts+axios+pinia to achieve senseless refresh How to use vue3+ts+axios+pinia to achieve senseless refresh May 25, 2023 pm 03:37 PM

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

See all articles