vue directly modifies the requested interface address on the server side

  • 2021-10-15 09:37:39
  • OfStack

A project may have many environments, such as development, testing, pre-production, production, etc. If every environment needs to be repackaged, it will be troublesome, so how to solve this problem

In vue and uniapp and under other frameworks, it can be solved as follows

Create a new env. json under static resources, vue project is created under public file, uniapp is created under static file

The file format is as follows


{
  "name": "development",
  "base": "/customer"
}

name represents the environment, which is convenient to directly view the current environment on the server. base is the requested address. If the server does not act as a proxy, base here should be the complete request address http://xxxxx.com/customer, similar to this

1 people always can not get this env. json address, because, here is because of asynchronous, if you want to solve, can be in main. js or main. ts how to operate


axios.get('./env.json')
 .then(function (res: any) {
  // handle success
      Vue.prototype.BASE_URL = res.data.base;
  new Vue({
   router,
   store,
   render: h => h(App)
  }).$mount('#app')
 })

So there is a problem is that 1 must be in the request for this json after the success of the project will start rendering, this time can do a loading animation, the request should be very fast, if the request fails, you can do an catch operation in axios, to a friendly prompt or something, re-request

So how to get it?

You can get it in the interceptor and then splice the request address

In the interceptor's js file


function getBaseUrl() {
  return Vue.prototype.BASE_URL
}

 Finally, in the incoming url When splicing, as follows 
url: getBaseUrl() + opts.url, // opts Is the passed parameter object 

In this way, you can request normally

Under the general development environment, you can configure your development address in env. json. Finally, after being packaged and deployed to the server automatically, if you want to change the address of other environments (test, pre-production and production), you can directly modify this env.json file on the server.

You're done, haha

The above is vue in the server side directly modify the request interface address details, more about vue modification request interface address information please pay attention to this site other related articles!


Related articles: