The development environment

configuration

We may encounter cross-domain problems when using the AXIos request interface in our vue project. To solve the cross-domain problem, we need to add the following code to the configuration file vue.config.js:

// Configure axiOS cross-domain requests
    devServer: {
        proxy: {
            '/api': { // Access path, you can set yourself,
                target: 'http://localhost:8081'.// Proxy interface, which is the prefix of the requested URL
                changeOrigin: true.// Enable proxy: a virtual server will be created locally, and then send the requested data and receive the requested data at the same time. In this way, there will be no cross-domain problem between the client and the server
                ws: true.// Whether to enable WebSockets
                pathRewrite: { // Access path rewrite
                    '^/api': ' '}}}}Copy the code

After modifying the configuration file, make sure to restart the project. Otherwise, the modification will not take effect.

request

After restarting the project, you can use AXIos to request the background interface:

axios("/api/activity").then((res) = >{
      console.log(res)
 })
Copy the code

Here call request when the requested url/API/activity, and the actual request is http://localhost:8081/activity, if you don’t want to every request take/API, so you can be in the main. Js, add the following code:

axios.defaults.baseURL = "/api";
Copy the code

This code prefixes each url you request with/API, so we can modify the above code again:

axios("activity").then((res) = >{
      console.log(res)
})
Copy the code

At this point, the above configuration solves the cross-domain problem in the development environment.

The online environment

Because there is no devServer in the online environment after the project is packaged and published, the requested URL will not be rewritten, so the error of interface 404 will be reported after the project is online.

We can solve this problem by dynamically adding the request URL prefix by determining whether the request environment is local or online.

// Determine whether the development environment is local or online
// Save the URL. If the url is local, the prefix is/API. If the URL is online, the prefix is online API address
let url = process.env.NODE_ENV == "development" ? "/api" : "http://api.yinbaole.com/";
Copy the code

Now let’s modify the above code:

axios.defaults.baseURL = url;
Copy the code

This solves the problem of requesting interface 404 in an online environment.

Also, because there is no devServer in the online environment, the solution to solve the cross-domain problem written above has become invalid. At this time, if the project and API address are not under the same server or cross-domain problem occurs due to domain name, protocol and other reasons, the cross-domain problem will still occur.

This problem can be solved by referring to axios official documents and sending data in Application/X-www-form-urlencoded format.

configuration

Create the axios.js file in the vue project with a custom path and write the following code. The following code integrates the above snippet of judging the development environment to make the code in main.js more concise.

import Axios from "axios";
// Import qs library
import qs from "qs";
// Determine whether the development environment is local or online
// Save the URL. If the url is local, the prefix is/API. If the URL is online, the prefix is online API address
let url = process.env.NODE_ENV == "development" ? "/api" : "http://api.yinbaole.com/";
const axios = Axios.create({
  // Send data in application/x-www-form-urlencoded format
  headers: {
    "content-type": "application/x-www-form-urlencoded",},// Request with cookie
  withCredentials: true});// Add a default prefix to each URL
axios.defaults.baseURL = url;

// Request interception
axios.interceptors.request.use((config) = > {
  // If the data sent is in FormData format, there is no need to use qs module for conversion
  if (typeof config.data == "object" && config.data.__proto__.toString() == "[object FormData]") return config;
  if (config.method == "post") {
    // If it is a POST request, use the QS module to convert the sent data
    config.data = qs.stringify(config.data);
  }
  return config;
});
export default axios;
Copy the code

After the configuration is complete, change the path from which axios is imported to the path of the axios.js file created in main.js. Requests already written in the project do not need to be changed.

Above, after completing the configuration, you can solve the cross-domain problem of AXIOS requests in the VUE project development environment and online environment.

reference

DevServer’s proxy is cross-domain

Vue implements cross-domain requests using AXIOS

Vue uses AXIos to present two solutions to cross-domain requests

Axios official documentation

Across the source | MDN resources sharing (CORS) – HTTP