vue-cli 3.0之跨域请求devServer代理配置

参考: https://blog.csdn.net/Liu_yunzhao/article/details/90520028

   https://www.cnblogs.com/xiangsj/p/8905648.html

概念

  同源策略

    同源策略是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。

    可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。
    所谓同源是指:协议、域名、端口都相同。

  跨域

    跨域就是不同源,就是不满足协议、域名、端口都相同的约定。

    

    如:看下面的链接是否与 http://www.test.com/index.html 同源?

      http://www.test.com/dir/login.html 同源
      https://www.test.com/index.html 不同源 协议不同(https)
      http://www.test.com:90/index.html 不同源 端口不同(90)
      http://www.demo.com/index.html 不同源 域名不同(demo)

    当协议、域名、端口中任意一个不相同时,就是不同源。若不同源之间相互请求资源,就算作跨域。

跨域请求devServer代理几种配置

  1.  先在项目的根目录下新建 vue.config.js 文件
  2.  在module.exports内设置devServer来处理代理

  

  3. 统一代理

    1). 设置 axios 的 baseURL 值(任意)

    

    axios.defaults.baseURL = '/api'

    这样会为所有的 请求url 前面都加上 ‘/api’,方便做 统一代理。

    假设请求的url地址为 /allin/policy/getProductInfo

   axios({
        ...
        url:'/allin/policy/getProductInfo',
        ...
    })

    那么真正发送的请求是:/api/allin/policy/getProductInfo

 devServer: {
     proxy: { //匹配规则
         '/api': {
             //要访问的跨域的域名
             target: 'http://www.test.com',
             ws: true,
             secure:false, // 使用的是http协议则设置为false,https协议则设置为true
             changOrigin: true, //开启代理
             pathRewrite: {
                 '^/api': ''
             }
         }
     }
 }

相当于请求遇见 /api 才做代理,但真实的请求中没有/api,所以在pathRewrite中把 /api 去掉, 这样既有了标识, 又能在请求接口中把 /api 去掉。

注意:
  pathRewrite:如果不写则只能修改代理的域名,如果写则可以修改代理的域名和后边的路径。

  4. 使用

     1).  在项目的根目录下新建 faceConfig.js 文件  

// 前端所有配置放这里
const faceConfig = () => {
    return {
        // 测试环境地址
         'devServer': '/api',
        //正式环境地址
        // 'devServer': window.location.origin+'/contentPath', // '/contentPath'为上下文路径,没有可不写
    }
}
module.exports = faceConfig()

    2).  在src下新建文件夹api,在api下新建index.js文件   

const API_ROOT = require('../../faceConfig.js').devServer
export default {
    info: `${API_ROOT}/users/info`,
}

    3).  组件中

    

<template>
    ···
</template>
<script>
    import API from '../../api/index.js' //路径根据自身情况修改

    ···
    getInfo(){
        let _this = this;
        _this.$get(API.info).then((res) => {
              ···      
        })
    }   
    ···
</script>   

解决线上环境跨域问题

  1. 前端先按 上述代理方式 做统一代理
  2. 后端 nginx 反向代理配置

    1). nginx 的 配置文件 xx.conf 的 server {} 里加如下:

location /api/ {
        // 把 /api 路径下的请求转发给真正的后端服务器
        proxy_pass http://xx.xx.xx.xx:5568;

        // 把host头传过去,后端服务程序将收到your.domain.name, 否则收到的是localhost:8080
        proxy_set_header Host $http_host;

        // 把cookie中的path部分从/api替换成/service
        proxy_cookie_path /api /;

        // 把cookie的path部分从localhost:8080替换成your.domain.name
        proxy_cookie_domain localhost:80 http://xx.xx.xx.xx:5568;
    }

    2). 重新启动一下 nginx 即可

/etc/init.d/nginx reload
原文地址:https://www.cnblogs.com/linjiangxian/p/13203835.html