Vue e-commerce project--axios secondary packaging

postman test interface

Just after testing with the postman tool, I found that the interface has changed.

The new interface is http://gmall-h5-api.atguigu.cn 

If the data code field returned by the server is 200, it means that the server returned the data successfully

Throughout the project, the interface prefix has the word /api

Axios secondary packaging 

XmlHttpRequest, fetch, JQ, Axios are all excellent network request libraries

Why is it necessary to repackage axios?

Request interceptor, response interceptor: request interceptor, can process some business before sending the request, response interceptor: when the server data is returned, it can process some things

First of all, we have not installed axiso, so we need to install it

Successful installation

In the project often api folder [axios] 

In the interface: the path has /api

baseURL:'/api'

It means that if we use the path /api/list/card in the future, /api can be ignored. it will automatically add 

Two intercept usages. If not, you can check the documentation Axios Chinese Documentation | Axios Chinese Network | Axios is a promise-based network request library that can be used in browsers and node.js (axios-http.cn)

Unified interface management 

The project is small: it is completely possible to send a request in the lifecycle function of the component

Large item: axios.get('xxx')

There is a problem with writing this way, that is, there is a cross-domain problem 

To solve cross-domain problems, you can use JSONP, CROS, proxy

Here we use a proxy method to solve cross-domain problems

That is to configure in vue.config.js

// 代理跨域
  devServer:{
    proxy:{
      '/api':{
        target:'http://gmall-h5-api.atguigu.cn',
        // pathRewrite:{'^/api':''}
      }
    }
  }

Successfully solved the problem of cross-domain 

Use of nprogress progress bar

nprogress is a progress bar plug-in, as long as it is used to refresh the page and display the progress

install this plugin

npm install nprogress --save

 

Take a look at what the nprogress we imported is what 

 We can clearly see that nprogress is an object. At the same time, start indicates the beginning of the progress bar and done indicates the end of the progress bar

 We can set the corresponding start and done of nprogress settings in the request interceptor and the corresponding interceptor, but we found that we have no effect. This is because we did not import styles.

 

This will work, but if it is actually developed. If you want to modify the color of this progress bar

 We only need to modify its underlying style 

Guess you like

Origin blog.csdn.net/weixin_64612659/article/details/130443547