Vue of Axios cross-domain solutions to problems

// axios 中的GET请求
axios.get('/user', {
    params: {
      ID: ‘001’
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

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

Scenario 1: Since the use of axios direct cross-domain access is not feasible, we need to configure the agent. Agent Reason can be solved: because the client requests data server is the presence of cross-domain issues, and between the server and the server can request data with each other, there is no cross-domain concept (if the server is not set permissions problem prohibit cross-domain), in other words, we can configure a proxy server can request data from another server, and then returns the requested data out to our proxy server, proxy server then returns the data to our clients, so that we can achieve accessing data across domains.

Preparation: Install the required middleware and plug-ins, such as axios, http-proxy-middleware and so on.

Specific cases: watercress here to access the Top250, for example, direct access as follows:

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

When performing npm run dev, console being given as follows:

Vue of Axios cross-domain solutions to problems

Facts have proved that direct cross-domain requests a problem does occur, the following steps to resolve the problem of cross-domain specific presentation:

The case of the above mentioned prerequisites have been installed complete, perform the following steps to resolve the issue:

1. Configure BaseUrl

In main.js, the configuration of the server prefix data (i.e. the fixed part), as follows:

// 项目入口,配置全局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'  //关键代码
Vue.config.productionTip = false

Vue.use(ElementUI);

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

// 默认进入商品模块
// VueRouter.push({ path: '/home' })

Key Code: axios.defaults.baseURL = '/ api', the role of each of our requests are sent with a prefix / api's.

2. Configure proxy

proxyTable field index.js config file in the folder, the process as follows:

  dev: {
    env: require('./dev.env'),
    port: 8090,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target:'http://api.douban.com/v2', // 你请求的第三方接口
        changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        pathRewrite:{  // 路径重写,
          '^/api': ''  // 替换target中的请求地址,也就是说以后你在请求http://api.douban.com/v2/XXXXX这个地址的时候直接写成/api即可。
        }
      }
    },
    // 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. In particular where use axios, modifications to the following url:

 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 issue has been resolved, the results are as follows:
[Note]: You must restart the project! !

principle:

Because we added a prefix to the url / api, we visit / movie / top250 on when to visit: localhost: 8080 / api / movie / top250 (where localhost: 8080 is the default IP and port).

Intercept / api in index.js in proxyTable in and put / api replaced all its previous contents became the target of, so the actual visit Url is http://api.douban.com/v2/movie/top250 .

So far, pure front-end proxy configuration axios solve cross-domain resolved.

According to the content of the comments section, distinguish between production and development environments, collective configured as follows:

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

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

console.log(isPro);

= {module.exports
the baseUrl: isPro '? HTTPS: //www.***/index.php/Official (line address )': 'API /'
}
2. The above documents incorporated main.js file inside, so can be defined to ensure that prefix matches dynamics of the production and development environments, code is 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 = to false;
axios.defaults.baseURL = apiConfig.baseUrl; // address of an interface
axios.defaults.withCredentials = false;
above two steps to resolve the cross-domain vue problems, and can be directly packaged to build online, any questions, please leave a message comments section, I hope for your help.

20 thumbs up

Guess you like

Origin blog.51cto.com/9161018/2477077