Vue's Axios Cross-domain Problem Solutions

Keywords: node.js axios Vue less npm

// GET requests in axios
axios.get('/user', {
    params: {
      ID: '001'
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// POST requests in axios
axios.post('/user', {
    firstName: '1',
    lastName: '2'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Option 1: Since direct cross-domain access using axios is not feasible, we need to configure the proxy.A proxy can solve this problem because there is a cross-domain problem when a client requests data from the server, and the server and the server can request data from each other. There is no cross-domain concept (if the server does not have permission issues to prohibit cross-domain), that is, we can configure a proxy server to request data from another server, and thenReturn the requested data to our proxy server, and the proxy server returns the data to our client so that we can access the data across domains.

Preparations: Install required middleware and plug-ins, such as axios,http-proxy-middleware, etc.

Specific cases: Here, for example, visit Douban Top250, direct access as follows:

axios.get("http://api.douban.com/v2/movie/top250")
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})

When executing npm run dev, the console reported the following error:

Direct requests have proven to have cross-domain issues. Here are the steps to address cross-domain issues:

Once the prerequisites mentioned above have been installed, the following steps can be taken to solve the problem:

1. Configure BaseUrl

In main.js, the prefix (that is, the fixed part) of the server on which the configuration data resides is coded as follows:

// Project entry, configure global vue
import Vue from 'vue'
import VueRouter from './router/routes.js'
import Store from './store/index.js'

import './assets/less/index.less'
import App from './App.vue'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'

import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'  //critical code
Vue.config.productionTip = false

Vue.use(ElementUI);

new Vue({
    router:VueRouter,
    store:Store,
    template:'<App/>',
    components: {App}
}).$mount('#app')

// Default Access to Commodity Module
// VueRouter.push({ path: '/home' })

Key code: axios.defaults.baseURL ='/api', which means that each request we send is prefixed with a / api.

2. Configure proxy

In the proxyTable field in the index.js file under the config folder, do the following:

  dev: {
    env: require('./dev.env'),
    port: 8090,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target:'http://api.douban.com/v2', //the third-party interface you requested
        changeOrigin:true, // A virtual server is created locally, then the requested data is sent, and the requested data is received at the same time, so there are no cross-domain issues with data interaction between the server and the server
        pathRewrite:{  // Path rewrite,
          '^/api': ''  // Replace the request address in the target, that is, you can write directly to / API when you request the address http://api.douban.com/v2/XXXXX in the future.
        }
      }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }

3. Where axios is used, modify the url as follows:

 axios.get("/movie/top250").then((res) => {
                  res = res.data
                  if (res.errno === ERR_OK) {
                     this.themeList=res.data;
                  }
                }).catch((error) => {
                  console.warn(error)
                })

4. After restarting the project, cross-domain issues have been resolved with the following results:
[Note] Project must be restarted!!

Principle:

Because we prefixed the url with / api, we accessed / movie / top250 as localhost:8080/api/movie/top250 (where localhost:8080 is the default IP and port).

The proxyTable in index.js intercepts/api and replaces/api and everything preceding it with the content in the target, so the actual access to Url is http://api.douban.com/v2/movie/top250.

At this point, pure front-end configuration proxy resolution axios is resolved across domains.

According to the content of the commentary area, distinguish the production environment from the development environment, and the collective configuration is as follows:

1. Create a configuration file for api.config.js in the config folder

const isPro = Object.is(process.env.NODE_ENV, 'production')

console.log(isPro);

module.exports = {
baseUrl: isPro ? 'https://www.***/index.php/Official (online address))' : 'api/'
}
2. Introduce the above file into the main.js file so that it can match the defined prefix of the production and development environment on the fly, coded as follows:

import Vue from 'vue'
import App from './App'
import router from './router'
import 'bootstrap/dist/js/bootstrap.min'
import 'bootstrap/dist/css/bootstrap.min.css'
import axios from 'axios'
import apiConfig from '../config/api.config'

Vue.prototype.$axios = axios;
Vue.config.productionTip = false;
axios.defaults.baseURL = apiConfig.baseUrl; //Configure interface address
axios.defaults.withCredentials = false;
These two steps will solve the cross-domain problem of vue, and you can package it online directly by build ing. If you have any problems, please leave a comment in the comments area. I hope it will help you.

Zan 20

Posted by elle_girl on Tue, 10 Mar 2020 16:14:44 -0700