• vue中解决跨域问题


    方法1.后台更改header

    header('Access-Control-Allow-Origin:*');//允许所有来源访问 
    header('Access-Control-Allow-Method:POST,GET');//允许访问的方式   

    方法2.使用JQuery提供的jsonp 

    methods: { 
      getData () { 
        var self = this 
        $.ajax({ 
          url: 'http://f.apiplus.cn/bj11x5.json', 
          type: 'GET', 
          dataType: 'JSONP', 
          success: function (res) { 
            self.data = res.data.slice(0, 3) 
            self.opencode = res.data[0].opencode.split(',') 
          } 
        }) 
      } 
    } 

    方法3.使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)

    例如请求的url:“http://f.apiplus.cn/bj11x5.json

    1、打开config/index.js,在proxyTable中添写如下代码:

    proxyTable: { 
      '/api': {  //使用"/api"来代替"http://f.apiplus.c" 
        target: 'http://f.apiplus.cn', //源地址 
        changeOrigin: true, //改变源 
        pathRewrite: { 
          '^/api': 'http://f.apiplus.cn' //路径重写 
          } 
      } 
    }

    2、使用axios请求数据时直接使用“/api”:

    getData () { 
     axios.get('/api/bj11x5.json', function (res) { 
       console.log(res) 
     })

    通过这中方法去解决跨域,打包部署时还按这种方法会出问题。解决方法如下:

    let serverUrl = '/api/'  //本地调试时 
    // let serverUrl = 'http://f.apiplus.cn/'  //打包部署上线时 
    export default { 
      dataUrl: serverUrl + 'bj11x5.json' 
    }

    附:

    方法二引入jq

    1.下载依赖

    cnpm install jquery --save-dev

    2.在webpack.base.conf.js文件中加入

    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
     ],

    3.在需要的temple里引入也可以在main.js里全局引入

    import $ from 'jquery'

    eg:

    <template>
      <div class="source">
          source{{data}}
      </div>
    </template>
    
    <script>
    import $ from 'jquery'
      export default({
        name:"source",
        data(){
          return{
            data:""
          }
        },
        created(){
          this.getData()
        },
        methods:{
          getData () {
            var self = this
            $.ajax({
              url: '你要请求的url',
              type: 'GET',
              dataType: 'JSONP',
              success: function (res) {
                self.data = res.result
              }
            })
          }
        }
      })
    </script>
    
    <style>
    
    </style>
  • 相关阅读:
    osds have slow requests
    supervisor 管理 celery
    guacamole部署
    openstack IPV6
    修复VSAN无法看到主机磁盘
    kolla之docker私有仓库创建
    CSS日食与太阳碰撞
    vue-devtools必备工具
    VUE在BODY上绑定enter事件
    VUE输入框显示时自动聚焦
  • 原文地址:https://www.cnblogs.com/ldlx-mars/p/7816316.html
Copyright © 2020-2023  润新知