• 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>
     
  • 相关阅读:
    Centos 6下使用cmake编译安装MariaDB
    mysql索引
    mysql基础指令知识
    git/github安装与使用教程
    Linux目录结构详解
    static关键字的作用(修饰类、方法、变量、静态块)
    Java中重载(overloading)和重写(Overriding)的区别
    @PropertySources和@ImportReSources注解
    @ConfigurationProperties注解和@Value注解的区别
    Java中数组的定义,初始化和使用
  • 原文地址:https://www.cnblogs.com/samve/p/14232758.html
Copyright © 2020-2023  润新知