Vue 2.x 如何利用proxyTable实现跨域请求(反向代理)

在项目运行的时候吗,不可缺少就是的设置反向代理的 
详细的文档 http-proxy-middleware 
下载的官方的脚手架打开文件的build/dev-server.js

搜索:(这个插件官方已经下载好了,只需要简单的配置一下就好的)

var proxyMiddleware = require('http-proxy-middleware')//获取插件
  • 1

添加下列代码: 
方法一:

app.use('/api', proxyMiddleware({
  target: 'http://xxxx.weddingee.com/', //域名的配置,
  changeOrigin:true,//通过设置changeOrigin:true 开启代理
}));
  • 1
  • 2
  • 3
  • 4

修改脚手架的东西后一定要npm run dev

全局配置axios的方法:

npm  install axios -D
  • 1

main.js

import axios from 'axios'
// Vue.prototype.axios = axios //组件调用this.axios.get(...)
// Vue.prototype.$ajax = axios  //换个名字 组件调用this.$ajax.get(...)
window.axios = axios;  //组件中调用 axios.get(...)
  • 1
  • 2
  • 3
  • 4
  • 5

组件中调用的方法:

getData(){
  axios.get('/api/work/home')  //api是前端自己添加的 
     .then(function (res) {
       console.log(res);
     })
     .catch(function (error) {
       console.log(error);
     });
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

方法二:config/index.js

   proxyTable: {
      firstProxy: {
        target: 'http://dingee.com/',
        filter(pathname, req) {
          //console.info('firstProxy',req)
          const isApi = pathname.indexOf('/api') == 0;
          const ret = isApi;
          return ret;
        },
        changeOrigin: true,
      },
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

修改脚手架的东西后一定要npm run dev 
调用的方法省略。

猜你喜欢

转载自blog.csdn.net/u013452337/article/details/80203843