Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use vue axios interceptor

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces "how to use vue axios interceptor" in detail, the content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use vue axios interceptor" can help you solve your doubts.

1. First of all, axios does not support the declaration of using the vue.use () method.

I looked at all the nearly identical axios documents and didn't mention this.

Suggested way

Declare the use of the following in main.js

Import axios from 'axios';Vue.prototype.$axios=axios

Then this.$axios can be called and used in other vue components.

two。 A little mention of vue cli scaffolding

The cross-domain problem of the local agent when the front end adjusts the back-end data interface. For example, I have to cross-domain when I access the local localhost interface http://40.00.100.100:3002/, which is equivalent to an error if the browser sets a threshold.

XMLHTTPRequest can not load http://40.00.100.100:3002/. Response to preflight request doesn't pass access control... .

Find out for yourself why cross-domain homology is not homologous. Configure proxyTable in webpack and OK it, as follows

Config/index.js

Dev: {add the following proxyTable: {'/ api': {target: 'http://40.00.100.100:3002/',// set the domain name and port number of the interface you call. Don't forget to add http changeOrigin: true, pathRewrite: {' ^ / api':'/'/ here it means to replace the address in target with'/ api'. When we drop the interface in the later components, we directly use api instead. For example, if I want to call 'http://40.00.100.100:3002/user/add', just write' / api/user/add''}.

Try it, cross-domain is successful, but note that this is only a cross-domain problem solved in the development environment (dev). If it is really deployed to a server in a production environment, if it is non-homologous or cross-domain, for example, if the server port we deploy is 3001, we need to jointly debug the front and rear ends. In the first step, we can test the front end in two environments: production production and development development. Configure the requested address API_HOST in config/dev.env.js and prod.env.js, that is, in the development / production environment, we use the proxy address api configured above in the development environment, and the normal interface address in the production environment, so configure it like this

Module.exports = merge (prodEnv, {NODE_ENV:'"development"', / / development environment API_HOST: "/ api/"}) module.exports = {NODE_ENV:'"production"', / / production environment API_HOST:' "http://40.00.100.100:3002/"'}

Of course, both development and production environments can request http://40.00.100.100:3002/ directly.

After configuration, when testing, the program will automatically determine whether it is the current development or production environment, and then automatically match API_HOST. We can use process.env.API_HOST in any component to use addresses such as

Instance.post (process.env.API_HOST+'user/login', this.form)

Then the second step is to configure the cros cross-domain on the backend server, which means that access-control-allow-origin:* allows all access. To sum up: in the development environment, our front end can configure a proxy proxy to cross-domain, and the real production environment also needs the cooperation of the back end.

Some god said: this method ie9 and the following does not work well, if compatibility is needed, the best way is to add a proxy in the server port at the back end, which is similar to the agent of webpack when developing.

3. The problem of axios sending get post request

When sending a post request, you usually set Content-Type and the type of content to be sent. Application/json means to send a json object but stringify it in advance. Application/xxxx-form means to send? A=b&c=d format, which can be formatted by qs. Qs will be installed automatically after installing axios. You only need to import it in the component.

Const postData=JSON.stringify (this.formCustomer); 'Content-Type':'application/json'} const postData=Qs.stringify (this.formCustomer); / / filtered into? & = format 'Content-Type':'application/xxxx-form'} use of 4.axios interceptor

When we visit an address page, we are sometimes asked to log in again and then visit the page, that is, authentication is invalid, for example, token is lost, or token still exists locally, but it is invalid, so just judging whether there is a local token value cannot solve the problem.

At this time, the server returned a 401 error when requesting, and there was an authorization error, that is, you do not have the right to access the page.

We can filter this situation before sending all requests and before manipulating the server response data.

/ / http request request interceptor. If there is a token value, configure the token value axios.interceptors.request.use (config = > {if (token) {/ / determine whether token exists before each request is sent. If so, add token to the header of the http request, instead of manually adding config.headers.Authorization = token;} return config for each request. }, err = > {return Promise.reject (err);}); / / the http response server responds to the interceptor, where it intercepts the 401 error and jumps back to the page to retrieve the tokenaxios.interceptors.response.use (response = > {return response) }, error = > {if (error.response) {switch (error.response.status) {case 401: / / here write the code router.replace ({path: 'login') to clear the token Query: {redirect: router.currentRoute.fullPath} / / Jump to the current page after a successful login})}} return Promise.reject (error.response.data)}) After reading this, the article "how to use vue axios interceptor" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it yourself. If you want to know more about the article, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report