zoukankan      html  css  js  c++  java
  • Vue中如何设置代理跨域请求数据

    webpack提供了配置代理的方法解决跨域:

    1、在vue-cli项目中打开webpack.dev.cof.js,如下:

    devServer: {
        clientLogLevel: 'warning',
        historyApiFallback: {
          rewrites: [
            { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
          ],
        },
        hot: true,
        contentBase: false, // since we use CopyWebpackPlugin.
        compress: true,
        host: HOST || config.dev.host,
        port: PORT || config.dev.port,
        open: config.dev.autoOpenBrowser,
        overlay: config.dev.errorOverlay
          ? { warnings: false, errors: true }
          : false,
        publicPath: config.dev.assetsPublicPath,
        proxy: config.dev.proxyTable,
        quiet: true, // necessary for FriendlyErrorsPlugin
        watchOptions: {
          poll: config.dev.poll,
        }
      }
    其中,proxy: config.dev.proxyTable为配置代理。 

    2、打开conifg目录下的index.js,在 proxyTable中进行配置:

    proxyTable: {
          '/api': {
            target: 'http://127.0.0.1:9999/',//设置你调用的接口域名和端口号,别忘了加http
            changeOrigin: true,
            secure: false,  // 如果是https接口,需要配置这个参数
            pathRewrite: {
              '^/api': '/'//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
            }
          }
        }
    3、配置好后,就可以获取后台提供的接口,然后进行页面的渲染了:
    <script>
    export default {
      methods: {
        getData() {
          this.$axios
            .get("/api/blog/data/")
            .then(function(response) {
              console.log(response);
            })
            .catch(function(error) {
              console.log(error);
            });
        }
      }
    };
    </script>
     
  • 相关阅读:
    定时任务时间表达式的规则(自己总结)
    本地vagrant配置虚拟域名的坑
    商派onex本地部署无法进入的问题
    一周一篇文章,立贴为证
    Ecshop安装的坑,建议不要使用!
    MYSQL查询语句优化
    .gitignore文件
    剖析Disruptor:为什么会这么快?(二)神奇的缓存行填充
    Disruptor 为什么这么快?
    一篇文章让你成为 NIO 大师 - MyCAT通信模型
  • 原文地址:https://www.cnblogs.com/samve/p/14232758.html
Copyright © 2011-2022 走看看