swiper---h5 跨域解决办法

swiper---h5  轮播插件

 

反向代理

一 : 说明

  • 解决跨域问题的方式 :

    • JSONP == > 只能处理 get 方式

    • CORS ==> 处理自己的服务器

    • 反向代理 ==> 也很常用

  • 说明

    1. 演示跨域问题

    2. 反向代理的原理

    3. 脚手架vue-cli 生成的项目中如何使用反向代理

二 : 演示跨域问题

测试真实请求接口 : https://api.douban.com/v2/movie/in_theaters

  1. todo-vuex 里的 app.vue 中 的js 代码区域演示

  2. 安装 axios

  3. 代码 :

    // 演示跨域问题
    /* eslint-disable */
    import axios from 'axios';

    axios.get('https://api.douban.com/v2/movie/in_theaters').then(res => {
     console.log(res)
    })

     

  4. 报错 :

    Access to XMLHttpRequest at 'https://api.douban.com/v2/movie/in_theaters' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  5. 报错原因

    - 项目运行在  http://localhost:8080
     // I Your application is running here: http://localhost:8080  
    - 发送ajax请求 : //域名是 https://api.douban.com/v2/movie/in_theaters
    - 出现跨域问题

     

三 : 反向代理的原理

 

四 : 演示

  • 修改 config/index.js 配置文件

 proxyTable: {
     '/myapi': {
       // 代理的目标服务器地址
       // https://api.douban.com/v2/movie/in_theaters
       // /myapi/movie/in_theaters
       target: 'https://api.douban.com/v2',
       pathRewrite: { '^/myapi': '' },

       // 设置https
       secure: false,
       // 必须设置该项
       changeOrigin: true
    }
  },
  • 最终代码

    // axios.get('https://api.douban.com/v2/movie/in_theaters').then(res => {
    axios.get("http://localhost:8080/api/movie/in_theaters").then(res => {
     console.log(res);
    });
  • 最终配置 cli2.x :

     proxyTable: {
         '/myapi': {
           // 代理的目标服务器地址
           // https://api.douban.com/v2/movie/in_theaters
           // /myapi/movie/in_theaters
           target: 'https://api.douban.com/v2',
           pathRewrite: { '^/myapi': '' },

           // 设置https
           secure: false,
           // 必须设置该项
           changeOrigin: true
        }
      },
  • 最终配置 3.X

    • 根目录下 新建一个 vue.config.js

    • 拷贝如下代码

    module.exports = {
     devServer: {
       proxy: {
         '/myapi': {
           // 代理的目标服务器地址
           // https://api.douban.com/v2/movie/in_theaters
           // /myapi/movie/in_theaters
           target: 'https://api.douban.com/v2',
           pathRewrite: { '^/myapi': '' },

           // 设置https
           secure: false,
           // 必须设置该项
           changeOrigin: true
        }
      }
    }
    }

    # 使用
    axios.get('http://localhost:8080/myapi/movie/in_theaters').then(res => {
     console.log(res)
    })
    axios.get('/myapi/movie/in_theaters').then(res => {
     console.log(res)
    })

     

  • 重新启动 : npm run dev

  •  

posted @ 2020-03-29 05:04  爱唱歌的小胡子  阅读(168)  评论(0编辑  收藏  举报