zoukankan      html  css  js  c++  java
  • vue 解决axios 跨域问题

    闲着没事,假期敲vue 请求数据,总结下vue跨越问题

    第一种.服务器服务器不支持跨域请求

      1.当跨域无法请求的时候我们可以修改工程下config文件夹下的index.js中的dev:{}部分。

        添加下面的代码:

       proxyTable: {
            '/api': {
                target: 'http://api.douban.com/v2',
                changeOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        },

     将target设置为我们需要访问的域名。

    2.然后在main.js中设置全局属性:

    Vue.prototype.HOST = '/api'

    3.我们就可以在全局使用这个域名了,如下:

    var url = this.HOST + '/movie/in_theaters'
        this.$http.get(url).then(res => {
          this.movieList = res.data.subjects;
        },res => {
          console.info('调用失败');
        });

    第二种:服务器端支持跨域

        String data = JsonUtil.toJsonNonNull(pubXtzdBos);
        
        OutputStream out = response.getOutputStream(); 
        
        out.write(data.getBytes("UTF-8"));//以UTF-8进行编码  
        
        response.setHeader("Access-Control-Allow-Origin", "*");
        //告诉浏览器编码方式  
        response.setHeader("Content-Type","text/html;charset=UTF-8" ); 

    就是能支持跨域那就可以使用jsonp来请求了。jsonp实际上就是通过添加script标签来添加的,

    请求回来的数据也是js格式。axios目前还不支持,只能自己手动创建script标签,把请求的地址赋给script标签的src属性,最后添加到head标签上,等到请求返回再把标签删掉:

       jsonpRequest: function (a, e) {
                this._ajaxTimer && clearTimeout(this._ajaxTimer);
                this._ajaxTimer = setTimeout(function () {
                    
                    var request_script = document.createElement('script');
                    request_script.setAttribute("id", "request_script");   
                    request_script.src = 'http://xxxx'+'&t=' + Date.now();
                    window.callback = function (response) {
                        // 移除脚本
                        document.body.removeChild(document.getElementById('request_script'));
                        console.log(response.content);
                    }
                    document.body.appendChild(request_script);
                }, 500);
            },

    讲真,本地开发适合第一种吧 然后可以正常使用axios进行ajax请求了,

             但这样只能在开发模式下才能使用。打包部署的时候建议使用nginx做代理

    ,我也没有试过第二种,也是查阅资料总结的,哈哈

  • 相关阅读:
    springmvc实现文件上传
    springmvc乱码及restful
    springmvc数据的处理
    springmvc跳转方式
    controller配置
    SpringMVC Annotation
    SpringMVC基本包
    第一章 面向对象软件工程与UML
    Oracle数据库之PL/SQL程序基础设计
    thinkphp5 给CSS JS 添加版本号
  • 原文地址:https://www.cnblogs.com/yf-html/p/8974525.html
Copyright © 2011-2022 走看看