vue跨域问题的由来以及解决方式

368 阅读1分钟

###什么是跨域? 浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域 域名:  主域名不同 www.baidu.com/index.html -->www.sina.com/test.js  子域名不同 www.666.baidu.com/index.html -->www.555.baidu.com/test.js  域名和域名ip www.baidu.com/index.html -->http://180.149.132.47/test.js 端口:  www.baidu.com:8080/index.html–> www.baidu.com:8081/test.js 协议:  www.baidu.com:8080/index.html–> www.baidu.com:8080/test.js 备注:  1、端口和协议的不同,只能通过后台来解决  2、localhost和127.0.0.1虽然都指向本机,但也属于跨域 ###vue cli4中解决跨域问题 在vue-cli4的项目中,

执行npm run serve时会把process.env.NODE_ENV设置为‘development’;

执行npm run build 时会把process.env.NODE_ENV设置为‘production’;

serviceUrl.js文件

let host = ''
let apiUrl = ''

if (process.env.NODE_ENV === 'development') {
    // 开发环境暴露的域名
    host = 'http://lvcai.xj128.com'
    apiUrl = host + '/api.html'
} else if (process.env.NODE_ENV === 'production') {
    // 生产环境暴露的域名
    host = window.host
    apiUrl = host + '/api.html'
}
export {
    host,
    apiUrl
}

//devServer开发环境下,会拦截的代理
 devServer: {
    disableHostCheck:true,
    port: 8888, // 端口号
    open: true, // 自动启动浏览器
    proxy: {
        '/test': {
            target: 'http://gftest.chabaobao.net',
            // target: 'http://gf.chabaobao.net',
            // target: 'http://192.168.31.142:8055',
            ws: true,
            pathRewrite: {'^/test' : ''}
        },
        '/production': {
            target: 'http://gf.chabaobao.net',
            ws: true,
            pathRewrite: {'^/production' : ''}
        }
    }
  },

跨域问题解决的根本 1.当第一次发起试探性请求,拼接的域名地址为:lvcai.xj128.com/test/a 2.当第二次发起真实性请求,拼接的域名地址为:lvcai.xj128.com/a