cause

One time, the backend brothers changed the online address, forcing me to change the interface address of the production environment and type a packet. After seeing this, the leader felt that the operation was very complicated, so he asked me if it was possible to change the interface address into a configuration item, and then change the address on the line at the back end, so that I didn’t need to re-type the front-end packet, but only need to modify the configuration item. My heart is desperate, but dare not ask a leader to want what bicycle, have to think about how to do 🤢

Normal interface encapsulation

Req.js (the first wrapper of Axios)

let severUrl;

// Environment switch
if (process.env.NODE_ENV == 'development') {
    
  // Development environment
  severUrl = 'xxx'
} else if (process.env.NODE_ENV == 'debug') {

  // Test the environment
  severUrl = 'xxx';
} else if (process.env.NODE_ENV == 'production') {

  // Production environment
  severUrl = 'xxx'
}
// Set the interface address
axios.defaults.baseURL = severUrl;
Copy the code

In general, axios obtains the interface by using NodeJS to judge the current environment and obtain the interface address matching the environment

thinking

How to leave a configuration item, write a js file in front of it, write a configuration object inside, and then reference it in this file?

It’s too much trouble to import, otherwise you can just mount it on the window global object.

Packing anywhere else will be garbled, where is the configuration?

The public folder will not be packed

Ho!!!!!! You can try

operation

Add config.js to the public folder

config.js

window._config={
  // Ajax interface configuration
  axiosUrl:"http://192.168.30.10:8080/alarm_analysis",}Copy the code

Add config.js to index.html in the public folder

Change req.js (first layer wrapper in AXIos)

let severUrl = window._config.axiosUrl;

// Set the interface address
axios.defaults.baseURL = severUrl;
Copy the code

In-person testing is effective in the development environment

Look again at the reasons for the success of the production environment

Index.html in the dist folder

As shown in the figure, config.js is the first script tag to be referenced in the body tag. According to the principle that JS code is executed from top to bottom, the modification of config.js to the window global object is also valid in the js file introduced later, so this method can be used for interface modification after packaging

There is no need to pack frequently because of the online address change at the back end, just need to change the configuration in the packed config.js, good!! ヾ(✿゚▽゚) Blue