vue-cli+axios+跨域

1、跨域

  指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。

2、同源策略

  是指协议,域名,端口都要相同,其中有一个不同都会产生跨域,在请求数据时,浏览器会在控制台中报一个异常,提示拒绝访问。

3、跨域问题怎么出现的

  开发一些前后端分离的项目,比如使用 SpringBoot + Vue 开发时,后台代码在一台服务器上启动,前台代码在另外一台电脑上启动,此时就会出现问题。
  比如:

    后台 地址为 http://192.168.70.77:8081
    前台 地址为 http://192.168.70.88:8080
  此时 ip 与 端口号不一致, 不符合同源策略,造成跨域问题

4、解决跨域问题

(1 )先引用axios

(2 )设置默认的前缀(公共的前缀,自动加在config.url前面的)  不需要则不设置

           axios.default.baseUrl='/api'

(3)配置创建vue.config.js

module.exports = {
    devServer: {
        proxy: {
            '/api': {
                // 此处的写法,目的是为了 将 /api 替换成https://www.cnblogs.com/
                target: 'https://www.cnblogs.com/',
                // 允许跨域
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/api': '/'
                }
            },
            '/haha': {
                // 此处的写法,目的是为了 将 /haha 替换成 https://element.eleme.cn/'
                target: 'https://element.eleme.cn/',
                // 允许跨域
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/haha': '/'
                }
            }
        }
    }
}
(4)使用
 this.$ajax
      .get('/api')
      .then(response => (this.info = response))
this.$ajax
      .get('/haha')
      .then(response => (this.more = response)).catch(err=>console.log(err))
4.1也可以用封装得方式
1)axios/index.js
import axios from 'axios'
export function requst (config){
    const Axios=axios.create({//实例化
      //baseURL:commonUrl,
      timeout:3000
    });
    Axios.interceptors.request.use(
        config=>{
            console.log(config.url);
            return config;
            //必须返回 不然没有请求参数了
        },err=>{
            return Promise.reject(err);
        });
    return Axios(config)//返回值是Promise对象
}
2)使用
 requst({url:'/api',param:''})
        .then(response => this.info = response)
        .catch(err=>console.log(err))
   requst({url:'/haha',param:''})
        .then(response => this.more = response)
        .catch(err=>console.log(err))
说明:
      1)  ’/api'可以换成有语义得字符串
 
 
 
原文地址:https://www.cnblogs.com/fanjiawen/p/14505511.html