zoukankan      html  css  js  c++  java
  • Vue中如何跨域请求数据(webpack、node.js和django中实现)

    一、webpack中设置跨域:

    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>

    二、axios请求的接口提供服务端设置跨域:

    1、axios不支持jsonp,因为axios的作者觉得jsonp不太友好,推荐用CORS方式更为干净;

    2、在使用axios发送请求时,服务器端设置

    res.header("Access-Control-Allow-Origin", "*")

    可以正确得到结果。

    3、实例:

    3.1 node.js代码

    let express = require("express");
    let app = express();
     
    app.use("/public", express.static("public"));
     
    app.get("/index", function(req, res, next){
        res.sendFile(__dirname + "/" + "views/index.html");
    });
     
    app.get("/get_data", function(req, res, next){
    	res.header("Access-Control-Allow-Origin", "*");
        let response = {
        	title: '在Vue中使用echarts',
        	xAxisData: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"],
        	seriesData: [10, 26, 16, 20, 16, 30]
        };
        res.type('application/json');
        res.jsonp(response);
    });
     
    app.listen(8000, function(){
        console.log("开始执行请求");
    });

    3.2 django代码:

    settings.py中:

    (1) 安装 django-cors-headers:

    pip install django-cors-headers

    (2) 添加到已安装的应用程序中:

    INSTALLED_APPS  =(
         ... 
        ' corsheaders ',
         ... 
    )

    (3) 添加中间件类来收听响应:

    MIDDLEWARE  = [
        ... 
        # 跨域请求中间件
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware',
         ... 
    ]

    注意:要放在中间件(common.CommonMiddleware)的上面,涉及到请求响应的顺序问题。

    (4) 跨域配置:

    在settings文件最后面添加如下所有代码

    # 跨域允许的请求方式,可以使用默认值,默认的请求方式为:
    # from corsheaders.defaults import default_methods
    CORS_ALLOW_METHODS = (
        'GET',
        'POST',
        'PUT',
        'PATCH',
        'DELETE',
        'OPTIONS'
    )
    
    # 允许跨域的请求头,可以使用默认值,默认的请求头为:
    # from corsheaders.defaults import default_headers
    # CORS_ALLOW_HEADERS = default_headers
    
    CORS_ALLOW_HEADERS = (
        'XMLHttpRequest',
        'X_FILENAME',
        'accept-encoding',
        'authorization',
        'content-type',
        'dnt',
        'origin',
        'user-agent',
        'x-csrftoken',
        'x-requested-with',
        'Pragma',
    )
    
    # 跨域请求时,是否运行携带cookie,默认为False
    CORS_ALLOW_CREDENTIALS = True
    # 允许所有主机执行跨站点请求,默认为False
    # 如果没设置该参数,则必须设置白名单,运行部分白名单的主机才能执行跨站点请求
    CORS_ORIGIN_ALLOW_ALL = True

    echarts.vue代码:

    <template>
      <div>
        <div id="myChart">
    
        </div>
      </div>
    </template>
    
    <script>
      export default {
        methods: {
          drawLine(){
            // 基于准备好的dom,初始化echarts实例
            let myChart = this.$echarts.init(document.getElementById('myChart'));
    
            this.$axios.get("http://127.0.0.1:8000/get_data")
              .then(function(res){
                // 绘制图表
                myChart.setOption({
                  title: { text: res.data.title },
                  tooltip: {},
                  xAxis: {
                    data: res.data.xAxisData
                  },
                  yAxis: {},
                  series: [{
                    name: '销量',
                    type: 'bar',
                    data: res.data.seriesData
                  }]
                });
              })
              .catch(function(err){
                console.log(err);
              })
          }
        },
        mounted(){
          this.drawLine();
        }
      }
    </script>
    
    <style>
    #myChart{
      height: 500px;
    }
    </style>
    
  • 相关阅读:
    第1条:考虑用静态工厂方法代替构造器
    代理模式(Proxy Pattern)
    out 和 ref 参数修饰符
    SQL Server 性能调优(一)——从等待状态判断系统资源瓶颈【转】
    Windows下获取Dump文件以及进程下各线程调用栈的方法总结(转)
    sql server内置函数
    ORA-16019 和 ORA-16018 错误的处理方法(转)
    marge into操作
    LogMiner配置使用手册
    课后作业
  • 原文地址:https://www.cnblogs.com/samve/p/10884808.html
Copyright © 2011-2022 走看看