search
HomeWeb Front-endVue.jsIn-depth analysis of axios global configuration, interceptors and proxy cross-domain proxy (picture and text)

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
This article is reproduced at:jianshu. If there is any infringement, please contact admin@php.cn delete
Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

See all articles

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor